I have a String "10010" and i am supposing that the string itself is a binary number. How can i convert the String "10010" to binary something like 0b10010 ?
2 Answers
You can pass the base to the to_i method:
"10010".to_i(2) #=> 18
Note that numbers are internally stored as binary. If you want to produce the output you specified, you would convert it back to a string using sprintf:
sprintf("%#b", 18) #=> "0b10010"
But if you don't care about the leading "0b" then you can also pass the base to the to_s method:
18.to_s(2) #=> "10010"
1 Comment
There is no notion of "decimal number" or "binary number" in Ruby objects. All there is is numbers (actually all numbers are binary at the low level, and necessary not at a higher level, but that is irrelevant to Ruby objects). "Decimal" or "binary" are only some ways to represent numbers. Therefore, you cannot convert something into a "binary number". All you can do is to convert it to a number.
18or do you want to prepend"0b"to the string?