I read a number "98" from a file, and tried to convert it to binary using input.to_i(2), but I get 0 that way.
input=File.read("input.dat")
puts "Input is: #{input}"
puts "Normal way is #{input.to_i(2)}"
puts "It works this way #{input.to_i.to_s(2)}"
puts "Calling the number directly works #{98.to_s(2)}"
Output is:
Input is: 98
Normal way is 0
It works this way 1100010
Calling the number directly works 1100010
to_i(2) interprets an expression in a string as a binary number, which should only consist of "0" and "1". Since "98" is invalid, the result becomes 0 by default, by design. (It could have been alternatively designed to return nil or raise an error, but somehow it is designed this way.)
To display a number as binary, you need to_s(2) because that gives the expression of the number in binary.
As a number, there is no distinction between binary number, decimal number etc. All there is is a number. What those notions with binary, decimal, etc. are about is the way they are expressed as a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With