How to Convert a Hexadecimal String to an Integer in Ruby?

Ruby hexadecimal string to integer conversion

In Ruby, you can use the Kernel#Integer method or the String#to_i method to convert a hexadecimal string to its integer equivalent. For example, you can do the following:

Convert Hexadecimal String With the 0x Radix Indicator

If a hexadecimal string is prefixed with the "0x" (or "0X") hexadecimal radix prefix, then only for the String#to_i method you need to specify the numeric base of 16 because the Kernel#Integer method automatically converts strings with radix indicators. For example:

puts "0xddd5".to_i(16) #=> 56789

puts Integer("0xddd5") #=> 56789

If you don't specify the numeric base for the String#to_i method, then it would return 0:

puts "0xddd5".to_i #=> 0

This is because the String#to_i method only interprets leading characters as numbers in a string (which in this case is 0), and ignores characters beyond the end of a valid number.

Convert Hexadecimal String Without a Radix Indicator

If the hexadecimal string is not prefixed with "0x" (or "0X") hexadecimal radix prefix, then you must specify the numeric base of 16 to both methods (i.e. Kernel#Integer and String#to_i), for example, like so:

puts "ddd5".to_i(16) #=> 56789

puts Integer("ddd5", 16) #=> 56789

Hope you found this post useful. It was published . Please show your love and support by sharing this post.