How to Convert an Octal Number to Decimal in Ruby

How do I convert an octal number to decimal in Ruby?

Use Ruby's octal integer literal syntax. Place a 0 before your number, and Ruby will convert it to octal while parsing:

v = 013 # => 11
a[v] # => 61

If the octal number is coming from an outside source like a file, then it is already a string and you'll have to convert it just like you did in your example:

number = gets.chomp # => "13"
v = number.to_i(8) # => 11
a[v] # => 61

Convert decimal into binary, octal, and hexadecimal?

You are missing the fact that 2 is... 2 in base 8, 16, or any base greater than 2. Try convert(42) for fun.

Converting Hexadecimal, Decimal, Octal, and ASCII?

class String
def convert_base(from, to)
self.to_i(from).to_s(to)
# works up-to base 36
end
end

p '1010'.convert_base(2, 10) #=> "10"
p 'FF'.convert_base(16, 2) #=> "11111111"

Convert Integer to Octal using class Integer and multiple methods

As suggested, do something like this:

class Integer
def to_base b
to_s b #same as self.to_s(b)
end

def to_oct
to_base 8 #same as self.to_base(8)
end
end

5.to_base 2 #=> "101"
65.to_oct #=> "101"

How to convert an integer in a base to a string

Numeric literals with a leading zero are considered to be octal (base 8) numbers.

The to_s method converts the numbers to the default decimal (base 10).

  • 21 octal is 17 decimal
  • 11 octal is 9 decimal

For the expected results, remove the leading zeroes.

Invalid octal digit error

Octal numbers use the digits 0 to 7. Maybe the error could be the digit 9, and digit 8 in your number.
If you want to pass the number '962833', try converting it first to a correct octal number with an online converter. Then add the leading '0' and pass it to your function.

ruby basic data type conversion

Having a 0 at the start of a number makes the interpreter/compiler interpret the following digits as an octal number sequence (base 8) not a decimal number sequence (base 10). Therefore the number you entered is an octal number and not decimal.

You can test this on a scientific calculator by putting it into octal mode and then switching to decimal.



Related Topics



Leave a reply



Submit