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
def toBinary ( n ) : NEW_LINE INDENT if ( n >= 1 or n <= 0 ) : NEW_LINE INDENT return " ERROR " ; NEW_LINE DEDENT frac = 0.5 ; NEW_LINE answer = " . " ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( len ( answer ) >= 32 ) : NEW_LINE INDENT return " ERROR " ; NEW_LINE DEDENT if ( n >= frac ) : NEW_LINE INDENT answer += "1" ; NEW_LINE n = n - frac ; NEW_LINE DEDENT else : NEW_LINE INDENT answer += "0" ; NEW_LINE DEDENT frac = ( frac / 2 ) ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT n = 0.625 ; NEW_LINE result = toBinary ( n ) ; NEW_LINE print ( " ( ▁ 0" , result , " ) ▁ in ▁ base ▁ 2" ) ; NEW_LINE m = 0.72 ; NEW_LINE result = toBinary ( m ) ; NEW_LINE print ( " ( " , result , " ) " ) ; NEW_LINE