Converting a Real Number ( between 0 and 1 ) to Binary 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 ; Input value
< ? php function toBinary ( $ n ) { if ( $ n >= 1 $ n <= 0 ) return " ERROR " ; $ frac = 0.5 ; $ answer = " . " ; while ( $ n > 0 ) { if ( strlen ( $ answer ) >= 32 ) return " ERROR " ; if ( $ n >= $ frac ) { $ answer . = "1" ; $ n = $ n - $ frac ; } else { $ answer . = "0" ; } $ frac = ( $ frac / 2 ) ; } return $ answer ; } $ n = 0.625 ; $ result = toBinary ( $ n ) ; print ( " ( 0" . $ result . " ) ▁ in ▁ base ▁ 2 STRNEWLINE " ) ; $ m = 0.72 ; $ result = toBinary ( $ m ) ; print ( " ( " . $ result . " ) " ) ; ? >