I wrote a function that I want to convert a fractional number into binary, but it does not work. The integer part of the number is converted to binary using the built-in function itoa(int, char array, 2); , for the remainder of the dot, I wrote my dec_bin function, in which the number is multiplied by 2, then the first character is remembered, changed to 0, and so on ...

 #include <iostream> #include <cmath> #include <string> using namespace std; string dec_bin(string dec, int steps) { double decimal = stof(dec); // 0.987 string str_decimal = ""; string decimal_bin = ""; for(int i = 0; i < steps; i++) { decimal *= 2; //1.974 str_decimal = to_string(decimal); decimal_bin += str_decimal[0]; // "1", "11", "111" ... str_decimal = str_decimal.replace(0, 1, "0"); // "0.974" decimal = stof(str_decimal); // 0.974 } return decimal_bin; } string float_to_bin(string input, int steps) { string result, whole; short sign = 0; // + by default char whole_bin[20]; if(input.find('-') != -1) // in "-1.974" sign = 1; // for -1.974 int point_pos = input.find('.'); if(point_pos != -1) { whole = input.substr(0, point_pos); string dec = "0" + input.substr(point_pos, input.size() - point_pos); //"0.987" } else { whole = input; } int int_whole = stoi(whole); itoa(int_whole, whole_bin, 2); //"" if(point_pos != -1) { string dec_bin; } if(point_pos != -1) { string whole_bin_res(20, whole_bin); // convert char to string result =whole_bin_res + "." + dec_bin(to_string(dec), steps); } else result = whole_bin; return sign, result; } int main(int argc, char* argv[]) { cout << "Enter a decimal number: "; string input = "12.987"; cout << float_to_bin(input, 3); return 0; } 
  • I do not see you check a bit. I would multiply by two, and check the first bit, i.e. type str_decimal = str_decimal + (( ((int)(floor(decimal ))) & 1 ) ? '0' : '1' ) discard the fractional part, and check bit 1. - nick_n_a
  • The algorithm is very confusing - too lazy to unravel. Choose one case, and simplify, there is a maximum ... two cycles and a couple of checks should remain. - nick_n_a
  • @nick_n_a it converts a string to a floating point number. I want to convert a decimal fractional number (12.987) to binary and return the string ("1100.111"). Even if I convert my input to a fractional number (via atof ()), I don’t know the function that could translate float into binary. - february
  • @nick_n_a bit checking is present, although perhaps at a primitive level. It is in a loop with 11 lines - Feb.
  • one
    .111 is .111 , not 0.987 7/8! = 987/1000 - vegorov

0