位操作 之三

本文提供两种不同的实现方式来解析IEEE 754标准下的32位浮点数,一种使用位运算直接计算浮点数值,另一种通过数组存储二进制位并进行逐位解析。

接位操作2.

   

#include <stdio.h>
#include <math.h>
#include <iostream>
using namespace std;
 
int main()
{
	int i,e,E,s,m,x;
	float s2=0,n;
	bool t;
    while(scanf("%X",&x)!=EOF)
	{
	t=x>>31;    //符号位
	E=x>>23;     
	e=(E&255)-127;	//译码 
	m=x&8388607;    //尾数
	n=m>>(23-e);     
	n=n+pow(2,e);
    //cout<<n<<endl;
	for(i=0;i<23-e;i++)
	{
		s=m&1;
		s2=(s2+s)*0.5;
		m=m>>1;
	}
	n=n+s2;
	if(t)
    	cout<<"-"<<n<<endl;
	else  cout<<n<<endl;
	}
	return 0;
}

下面这个是 用数组存储的,比较好理解。

#include<iostream>
#include<cstring>
#include<stdio.h>
#include<cstdlib>
#include<cmath>
int a[33];
unsigned int y,x;
using namespace std;
void init()
{
	if(x<=0xF)
	y=4;
	else if(x<=0xFF)
	y=8;
	else if(x<=0xFFF)
	y=12;
	else if(x<=0xFFFF)
	y=16;
	else if(x<=0xFFFFF)
	y=20;
	else if(x<=0xFFFFFF)
	y=24;
	else if(x<=0xFFFFFFF)
	y=28;
	else 
	y=32;
}
int main()
{
	int sum=0;
	float t1,sum1,sum2;
    int m;
    unsigned int temp,t;
    while(scanf("%x",&x))
    {
    t1=1,sum1=0;sum=0,sum2=0;
    init();
    int i,j;
    memset(a,0,sizeof(a));
    for(i=0;i<y;i++)
    {
        temp=x;
        temp=temp>>i;
        a[32-i]=temp&1;

    }
   /*
     输出二进制位数 
  */
    for(i=1;i<=32;i++)
    cout<<a[i];
    cout<<endl;
    for(i=9;i>=2;i--)
    {
        t=1;
        for(j=0;j<9-i;j++)
        t*=2;
        sum+=t*a[i];
    }
    m=sum-127;//移动的位数 
    //cout<<m<<endl;
    
    //if(m>0)
    sum2=pow(2,m);
    for(i=1;i<=9;i++)
    a[i]=0;
    for(i=0;i<23-m;i++)
    {
    	sum1=(sum1+a[32-i])*0.5;
    }
    sum1+=sum2;
    if(a[1]==1)sum1=-sum1;
    cout<<sum1<<endl;
   }
    return 0;
}
/*
BD400000
10111101010000000000000000000000
0.046875
BD9DE0CB
10111101100111011110000011001011
0.0770889
3C181F9A
00111100000110000001111110011010
0.00928488
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sunshine_gao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值