5.2-浮点数转二进制

Given a (decimal - e.g. 3.72) number that is passed in as a string, print the binary representation. If the number can not be represented accurately in binary, print “ERROR”

参考http://hawstein.com/posts/5.2.html

整数部分:如果除二余1,该位置1;否则置0。 然后整数部分右移一位,直到小于0。 这里添加0或1的顺序从右往左。

小数部分:先小数部分*2,如果比1大,则置1,并且减去1;否则置0。直到小数部分小于0。这里添加0或1的顺序从左往右。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

string print_binary(string str_decimal)
{
    int pos = str_decimal.find('.', 0);
    int intpart = atoi(str_decimal.substr(0, pos).c_str());
    double decpart = atof(str_decimal.substr(pos, str_decimal.length()-pos).c_str());
    string int_str, dec_str;
    while(intpart > 0)
    {
        if(intpart%2==1)
         int_str = "1"+ int_str;
        else
         int_str = "0"+ int_str;
        intpart >>= 1;
    }
    while(decpart > 0)
    {
        if(dec_str.length() > 32)
         return "ERROR";
        decpart *= 2;
        if(decpart >= 1)
        {
            dec_str += "1";
            decpart -= 1;
        }
        else
            dec_str += "0";
    }
    return int_str + "." + dec_str;
}
int main()
{
    string str_decimal = "6.5";
    cout<<print_binary(str_decimal)<<endl;
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值