将float型变量转换成32位二进制数,并保存在char型数组中

       受到帖子 http://blog.csdn.net/demon__hunter/article/details/3566232启发,

       用C语言写了如下代码,将一个float型变量的内容转换为32位0、1串并输出

       以float型变量(其值为4.25)为例

#include 
#include 

#define N 32
#define BigEnd 0
#define LittleEnd 1

void ReverseArray( char *, int len );
int	JudgeBigOrLittleEnd();

int main()
{
	float fVal = 4.25;
	char *p = NULL;
	
	int i = 0, j = 0;
	char mask = 0x01;
	char str[N+1] = "";
	printf("fVal = %f\n",fVal);
	
	if ( BigEnd == JudgeBigOrLittleEnd() )
		printf("当前CPU为大端模式\n");
	else
		printf("当前CPU为小端模式\n");
		
	p = (char *)&fVal;	//整形变量地址转换为char *
	for (i=0; i<4; i++)
	{
		mask = 0x01;
		for (j=0; j<8; j++)
		{
			if (*(p+i) & (mask<


运行结果:

        mahone@lte:~/ws/LinuxC/projects/float2binary$ ./a.out
        fVal = 4.250000
        当前CPU为小端模式
        01000000100010000000000000000000
        01000000 10001000 00000000 00000000

解析:

由于float型变量,值为4.25时,其在内存中存储方式为

01000000100010000000000000000000

第一位为0,表示正,接下来8位为10000001,即1*2^7 + 1 = 129,指数位偏移位数计算方式为129-127 = 2(小数点向右)

低23位为小数部分: 00010000000000000000000,添上小数点,加上小数点前面的1,即

1.0001

小数点右移两位,加上符号,最终为

100.01

也即:1*2^2 + 1*2^(-2) = 4 + 1/4 = 4.25

你可能感兴趣的:(将float型变量转换成32位二进制数,并保存在char型数组中)