Converting an integer to a hexadecimal string in Ruby

RubyHexBase Conversion

Ruby Problem Overview


Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?

Something like the opposite of String#to_i:

"0A".to_i(16) #=>10

Like perhaps:

"0A".hex #=>10

I know how to roll my own, but it's probably more efficient to use a built in Ruby function.

Ruby Solutions


Solution 1 - Ruby

You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s

Solution 2 - Ruby

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

Solution 3 - Ruby

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

Solution 4 - Ruby

Here's another approach:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

Solution 5 - Ruby

Just in case you have a preference for how negative numbers are formatted:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt HaughtonView Question on Stackoverflow
Solution 1 - RubyJeanView Answer on Stackoverflow
Solution 2 - RubyflxkidView Answer on Stackoverflow
Solution 3 - RubyLriView Answer on Stackoverflow
Solution 4 - RubyUltrasaurusView Answer on Stackoverflow
Solution 5 - Rubytool makerView Answer on Stackoverflow