C语言不用指针只用数组和移位操作将二进制转化为十进制IEEE32浮点数

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int main(int argc,char **argv){
	float f=-3.14;
	unsigned char *const pf=(unsigned char*)&f,*p;
	unsigned char table[4];
	unsigned i;//cycle variable
	unsigned whole_value;
	unsigned sym_value;//symbol bit
	unsigned exp_value;//exponent 
	unsigned mat_value;//mantissa
	
	//show all bytes of f 
	printf("the value of variable f is: %g\t\n",f);
	printf("all bytes of variable f are(from high byte to low byte):\n"); 
	for(p=pf+3;p>=pf;printf("0x%0x\t",*p--));
	printf("\012");
	
	//save the above variables to array(low byte first)
	for(p=pf,i=0;i<4;table[i++]=*p++);

	//anti solution the variable of f(solution 1)
	sym_value=table[3] >> 7;
	exp_value=((table[3] & 0x7F) << 1) + (table[2] >> 7); 
	mat_value=((table[2] & 0x7F) << 16) + (table[1] << 8) + table[0];	
	printf("the value of solution 1:%g\n",pow(-1,sym_value)*(1+mat_value*pow(2,-23))*pow(2,exp_value-127));
	
	//anti solution the variable of f(solution 2)
	whole_value=(table[3] << 24) + (table[2] << 16) + (table[1] << 8) + table[0];
	sym_value=whole_value >> 31;
	exp_value=whole_value << 1 >> 24;
	mat_value=whole_value << 9 >> 9;
	printf("the value of solution 2:%g\n",pow(-1,sym_value)*(1+mat_value*pow(2,-23))*pow(2,exp_value-127));
	
	return EXIT_SUCCESS;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值