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;
}