-2

I'm trying to convert the integer 1101 in binary to 13 in decimal. I can do:

0b1101.to_s(10) # => 13

How would I take 1101 and add the "0b" to the front? Is that possible?

sawa
  • 165,429
  • 45
  • 277
  • 381
mhkna
  • 53
  • 1
  • 5
  • 2
    `0b1101` is just another way to write `13`. In other words: `0b1101` already is `13`. Calling `to_s` will just convert it to a string, i.e. `"13"`. – Stefan Oct 19 '17 at 20:18

2 Answers2

2

You don't need to add anything to the string. Just call #to_i on it with the desired base as a parameter:

"1101".to_i(2) # => 13
sawa
  • 165,429
  • 45
  • 277
  • 381
moveson
  • 5,103
  • 1
  • 15
  • 32
1

If I get what you're trying to do this should work

Integer("1101", 2) # => 13
sawa
  • 165,429
  • 45
  • 277
  • 381
Ursus
  • 29,643
  • 3
  • 33
  • 50