Solution
#include <ctype.h>
#include <iostream>
#include <string>
using namespace std;
bool convert_int(string &str, int &num)
{
char c;
int base = 1;
int i = 0;
num = 0;
while(i < str.length())
{
c = str.at(i);
if(isdigit(c)){
num += (c - '0') * base;
base *= 10;
}
else{
return false;
}
i++;
}
return true;
}
bool convert_fraction(string &str, double &num)
{
char c;
double base = 0.1;
int i = 0;
int len = str.length();
num = 0;
while(i < len)
{
c = str.at(i);
if(isdigit(c)){
num += (c - '0') * base;
base /= 10;
}
else{
return false;
}
i++;
}
return true;
}
bool convert_to_decimal(string &str, int &sign, int &num, double &fraction )
{
int len;
char tmp[256];
int dot_idx = 0;
len = str.length();
if(len == 0){
return false;
}
// parse sign
if(str.find_first_of('-') == 0){
if(len == 1){
return false;
}
dot_idx = 1;
sign = -1;
}
else{
sign = 1;
}
// parse dot
int idx = str.find_first_of('.');
if(idx != string::npos){
if(idx == 1 && sign == -1){ // "-."
return false;
}
if(idx == 0 && sign == 1){ // "."
return false;
}
// extract fraction
string frac;
// idx + 1 to skip dot
str.copy(tmp, len - idx - 1, idx + 1);
tmp[len - idx - 1] = '\0';
frac = tmp;
if(!convert_fraction(frac, fraction)){
return false;
}
}
else{ // no fraction part
idx = len;
}
// extract integer
string integer;
// dst, count , offset
str.copy(tmp, idx - dot_idx, dot_idx);
tmp[idx -dot_idx] = '\0';
integer = tmp;
if(!convert_int(integer, num)){
return false;
}
return true;
}
bool binary_representation(string &res, string &str)
{
int sign;
int integer;
double fraction;
int dot_idx = 0;
res = "";
if(convert_to_decimal(str, sign, integer, fraction ) != false){
cout << "sign : " << sign << endl;
cout << "integer part: " << integer << endl;
cout << "fraction part: " << fraction << endl;
if(sign == -1){
res += "-";
dot_idx = 1;
}
if(integer != 0){
while(integer > 0){
string tmp = "";
tmp += integer % 2 + '0';
res.insert(dot_idx, tmp);
integer /= 2;
}
}
else{
res += "0";
}
if(fraction > 1e-15){
res += '.';
}
while(fraction > 1e-15){
if(fraction * 2 > 1 - (1e-15)){
res.append("1");
fraction *= 2;
fraction -= 1;
}
else{
res.append("0");
}
}
}
else{
res = "ERROR" ;
return false;
}
return true;
}
int main(int argc, char* argv[])
{
string str = "-123.75";
string res;
binary_representation(res, str);
cout << res << endl;
return 0;
}
Output
sign : -1
integer part: 321
fraction part: 0.75
-101000001.11
Problem
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”