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"
Integer:
Take the remainder of 2, move one to the right, and repeat until the integer is 0.
Decimal part:
Multiply by 2 to see if the result is greater than 1. If it is greater than 1, then 2 ^-1 places the upper 1; otherwise, it is 0. If the value is greater than 1, the result is reduced by 1 and then multiplied by 2. Otherwise, the result is multiplied by 2 to continue the judgment until the decimal part exceeds 32 bits, and an error is returned.
For example: 0.75d = 0.11b, multiply by 2 is actually equivalent to shift left. If the result is greater than 1, it means that 2 ^-1 is 1, then subtract 1, continue multiply by 2, and the result is equal to 1, it indicates that 2 ^-2 is 1 and there is no decimal place behind it.
#include<iostream>#include<string>#include<stdlib.h>using namespace std;string func(const string &str){ string strInt; string strDou; string::size_type idx = str.find(‘.‘); if(idx == string::npos) { strInt = str; } else { strInt = str.substr(0,idx); strDou = str.substr(idx); } int intPart = atoi(strInt.c_str()); double douPart; if(!strDou.empty()) { douPart = atof(strDou.c_str()); } else { douPart = 0.0; } string strIntB,strDouB; while(intPart!=0) { if((intPart&1)>0) { strIntB = ‘1‘+strIntB; } else { strIntB = ‘0‘+strIntB; } intPart=intPart>>1; } while(!(douPart>-10e-15 && douPart<10e-15)) { if(douPart*2>1) { strDouB = ‘1‘+strDouB; douPart = douPart*2-1; } else if((douPart*2-1)>-10e-15 && (douPart*2-1)<10e-15) { strDouB = ‘1‘+strDouB; break; } else { strDouB = ‘0‘+strDouB; } if(strDouB.size()>32) { return "ERROR"; } } if(strDouB.empty()) { return strIntB; } else { return (strIntB+‘.‘+strDouB); }}int main(){ string str("3.75"); cout<<func(str)<<endl; return 0;}