Converting a hexadecimal number to binary in ruby

You can also do:

num = "0ff"
num.hex.to_s(2).rjust(num.size*4, '0')

You may have already figured out, but, num.size*4 is the number of digits that you want to pad the output up to with 0 because one hexadecimal digit is represented by four (log_2 16 = 4) binary digits.


You'll find the answer in the documentation of Kernel#sprintf (as pointed out by the docs for String#%):

http://www.ruby-doc.org/core/classes/Kernel.html#M001433


This is the most straightforward solution I found to convert from hexadecimal to binary:

['DEADBEEF'].pack('H*').unpack('B*').first # => "11011110101011011011111011101111"

And from binary to hexadecimal:

['11011110101011011011111011101111'].pack('B*').unpack1('H*') # => "deadbeef"

Here you can find more information:

  • Array#pack: https://ruby-doc.org/core-2.7.1/Array.html#method-i-pack
  • String#unpack1 (similar to unpack): https://ruby-doc.org/core-2.7.1/String.html#method-i-unpack1

Tags:

Ruby