Home > Back-end >  How to print octal value or binary value in ruby programming language?
How to print octal value or binary value in ruby programming language?

Time:09-13

How do i just enter octal value or binary value to print in ruby as Integer i tried that an it works but is there any other way?

puts '1011'.to_i(2) # => 11

CodePudding user response:

try this

# Binary to Integer
# puts 0b(binary)
puts 0b1011 => 11
puts 0b1011.class => Integer

# Octal to Integer
# puts (octal_value)
puts 0366 => 246
puts 0b1011.class => Integer

# Hex to Integer
# puts 0x(hex value)
puts 0xff => 255
puts 0xff.class => Integer

CodePudding user response:

A few ways. You can either prepend your number with radix indicators (where 0= octal or 0b = binary):

01011
#=>  521

0b1011
#=>  11

...or you can use Integer() if you want and prepend those radix indicators to a string:

number = '1011'
Integer("0#{number}")
#=>  521

Integer("0b#{number}")
#=>  11

There's also the oct method for converting string to octal but I don't believe it has a binary counterpart:

'1011'.oct
#=>  521
  • Related