1

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 ?

6
  • please define "something like 0b10010", do you want to covert it to 18 or do you want to prepend "0b" to the string? Commented Sep 16, 2014 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 Commented Sep 16, 2014 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. Commented Sep 16, 2014 at 11:40
  • 1
    @bhanua1 why do you need a "binary number", what are you trying to do? Commented Sep 16, 2014 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)]+/ Commented Sep 16, 2014 at 12:23

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer and explanation too. :-)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.