#include “stdafx.h”
int Float2Binary(const double src, char* dest, int* len)
{
int intNum = 0;
double floatNum = 0.0f;
int i= 0,j=0;
int tmp = 0;
bool record = false;
intNum = (int)src;//取整部分
floatNum = intNum == 0 ? src : src-intNum; //取小数部分
for(i=63;i>=0;i–) { //转整数部分
tmp = (int)(intNum>>i&1);
if (tmp || record){ //tmp第一次出现1时record = true
dest[j] = tmp +’0′;
j++;
record = true;
}
}
if (!record){ //整数部分等于0
dest[j] = 0 +’0′;
j++;
}
dest[j] = ‘.’;
j++;
if (!floatNum){ //小数部分等于0
dest[j]=0;
return 1;
}
intNum = 0;
while(floatNum){ //转小数部分
floatNum = floatNum*2;
intNum = (int)(floatNum);
if (intNum<0)
dest[j]=intNum+2+’0′; //负整数-1转为正整数1
else
dest[j]=intNum+’0′;
floatNum = floatNum – intNum;
j++;
};
*len = j;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
double src = 8.124986653231321313131443523523;
int a = (int)src;
printf(“%d\n”,a);
printf(“%f\n\n”,src-a);
int len = 0;
char dest[256]={0};
Float2Binary(src,dest,&len);
for (i=0; i<len; i++){
printf(“%c”,dest[i]);
}
getchar();
return 0;
}