Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex to decimal in Ruby

Tags:

ruby

I have hex numbers, and I want to convert them into decimal numbers. For example, 01 -> 1, 09 -> 9, 12 -> 18.

I tried:

01.unpack("n")

but that failed.

"01".unpack("n") # => [12337]

That is not what I want.

Do you know the correct answer?

like image 458
user2909180 Avatar asked Mar 07 '18 10:03

user2909180


1 Answers

String#to_i accepts an extra argument, which is the number base to use. Hexadecimal is base 16, so the following will work for you:

"01".to_i(16)

Calling the Integer function on it will also work, so long as the number has an 0x prefix:

Integer("0x01")
like image 53
Aaron Christiansen Avatar answered Nov 14 '22 16:11

Aaron Christiansen