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 ?
Asked
Active
Viewed 5,501 times
1
-
please define *"something like 0b10010"*, do you want to covert it to `18` or do you want to prepend `"0b"` to the string? – Stefan Sep 16 '14 at 11:01
-
@Stefan I want to convert that string into a binary number instead of using to_i(2) which results a decimal equivalent thats why i typed as 0b10010 – bhanu Sep 16 '14 at 11:35
-
That is incorrect, numbers are all stored in binary. There is no such thing as a 'decimal equivalent'. See @sawa's answer. – Mark Thomas Sep 16 '14 at 11:40
-
1@bhanua1 why do you need a "binary number", what are you trying to do? – Stefan Sep 16 '14 at 12:01
-
@Stefan i want to perform a XOR operation on two binary numbers which are actually user input taken as strings and by the way, please tell me how to validate that user input using regex, if you know. i tried something like input_str == /[(0|1)]+/ – bhanu Sep 16 '14 at 12:23
-
@bhanua1 you should have added those details to your question. Please open a new question regarding the binary regex and perhaps another one regarding the XOR operation if this is still unclear. – Stefan Sep 16 '14 at 12:47
2 Answers
6
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"

Mark Thomas
- 37,131
- 11
- 74
- 101
4
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.

sawa
- 165,429
- 45
- 277
- 381