Converting a Real Number ( between 0 and 1 ) to Binary String | C ++ program to Binary real number to String . ; Function to convert Binary real number to String ; Check if the number is Between 0 to 1 or Not ; Setting a limit on length : 32 characters . ; compare the number to .5 ; Now it become 0.25 ; Driver code ; Input value
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; string toBinary ( double n ) { if ( n >= 1 n <= 0 ) return " ERROR " ; string answer ; double frac = 0.5 ; answer . append ( " . " ) ; while ( n > 0 ) { if ( answer . length ( ) >= 32 ) return " ERROR " ; if ( n >= frac ) { answer . append ( "1" ) ; n = n - frac ; } else { answer . append ( "0" ) ; } frac /= 2 ; } return answer ; } int main ( ) { double n = 0.625 ; string result = toBinary ( n ) ; cout << " ( 0" << result << " ) ▁ in ▁ base ▁ 2" << endl ; double m = 0.72 ; result = toBinary ( m ) ; cout << " ( " << result << " ) " << endl ; }