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; }
str_decimal = str_decimal + (( ((int)(floor(decimal ))) & 1 ) ? '0' : '1' )
discard the fractional part, and check bit 1. - nick_n_a.111
is.111
, not0.987
7/8! = 987/1000 - vegorov