C,浮點數轉二進位制數(正負數均可)
#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; }