您可以通过几个中间步骤完成您的要求。首先将您的 float 转换为 int,然后将该 int 转换为二进制表示。从那里,您可以将结果值分配给您的位字段。该答案仅涉及中间步骤。
此处的信息提供了5.2 float
由 表示的背景和佐证01000000101001100110011001100110
。可以通过多种不同的方式将浮点数分解为二进制表示。这只是一种实现或表示。反转这个过程(即从二进制回到浮动)需要遵循链接中列出的相同规则集,向后。
注意:字节序也是一个因素,我是在 Windows/Intel 环境中运行的。
这是代码:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
const char *byte_to_binary32(long int x);
const char *byte_to_binary64(__int64 x);
int floatToInt(float a);
__int64 doubleToInt(double a);
int main(void)
{
long lVal, newInt;
__int64 longInt;
int i, len, array[65];
int len1, len2, len3, len4, len5, len6;
char buf[100];
char quit[]={" "};
float fNum= 5.2;
double dpNum= 5.2;
long double ldFloat;
while(quit[0] != 'q')
{
printf("\n\nEnter a float number: ");
scanf("%f", &fNum);
printf("Enter a double precision number: ");
scanf("%Lf", &ldFloat);
newInt = floatToInt(fNum);
{
//float
printf("\nfloat: %6.7f\n", fNum);
printf("int: %d\n", newInt);
printf("Binary: %s\n\n", byte_to_binary32(newInt));
}
longInt = doubleToInt(dpNum);
{
//double
printf("double: %6.16Lf\n", ldFloat);
printf("int: %lld\n", longInt);
printf("Binary: %s\n\n", byte_to_binary64(longInt));
/* byte to binary string */
sprintf(buf,"%s", byte_to_binary64(longInt));
}
len = strlen(buf);
for(i=0;i<len;i++)
{ //store binary digits into an array.
array[i] = (buf[i]-'0');
}
//Now you have an array of integers, either '1' or '0'
//you can use this to populate your bit field, but you will
//need more fields than you currently have.
printf("Enter any key to continue or 'q' to exit.");
scanf("%s", quit);
}
return 0;
}
const char *byte_to_binary32(long x)
{
static char b[33]; // bits plus '\0'
b[0] = '\0';
char *p = b;
unsigned __int64 z;
for (z = 2147483648; z > 0; z >>= 1) //2^32
{
*p++ = (x & z) ? '1' : '0';
}
return b;
}
const char *byte_to_binary64(__int64 x)
{
static char b[65]; // bits plus '\0'
b[0] = '\0';
char *p = b;
unsigned __int64 z;
for (z = 9223372036854775808; z > 0; z >>= 1) //2^64
{
*p++ = (x & z) ? '1' : '0';
}
return b;
}
int floatToInt(float a)
{
return (*((int*)&a));
}
__int64 doubleToInt(double a)
{
return (*((__int64*)&a));
}
这是结果的图像(针对 32 位和 64 位更新):