65,168
社区成员




int ftostr( char *pBuf, int nSize, float fNum )
float fTest = 54345.3435f;
unsigned char *pData = (unsigned char*)&fTest;
float fRes = 1.0f; // 表示1.xxx
// 提取尾数
for ( unsigned int i = 0; i < 23; ++i )
{
// 确定尾数所在的字节,并计算当前的位在字节中的位置
unsigned char nBit = pData[ 2 - ( i + 1 ) / 8 ] << ( i + 1 ) % 8;
nBit >>= 7;
fRes += (float)nBit / ( 2 << i ); // 2<<i相当于2^i
}
// 提取阶码,阶码位于第30位到第23位
unsigned char nExp = pData[3];
nExp <<= 1; // 除掉附号位
nExp |= ( pData[2] >> 7 ); // 与下个字节的首位合并,组成阶码
nExp -= 0x7F; // 减127得到原阶数
fRes *= pow( 2.0f, (float)*(char*)&nExp );
// 提取符号位,位于最高位,第31位
if ( pData[3] & 0x80 )
{ // 最高位为1则为负,为0则为正
fRes = -fRes;
}
cout << setprecision(10) << fTest << "->" << fRes;
//由数值转换为字符串.
//浮点数需要预先设置精度.
#include <string>
#include <sstream>
using namespace std;
template <typename T>
std::string ValueToStr(T value)
{
ostringstream ost;
ost << value;
return ost.str();
}
//=================================
#include "main.h"
#include <iostream>
using namespace std;
int main()
{
long testValue = 123456789;
string hello = ValueToStr(testValue);
cout << "value : " << testValue << endl;
cout << "string : " << hello.c_str() << endl;
}