Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a hexadecimal number to binary in ruby

Tags:

ruby

I am trying to convert a hex value to a binary value (each bit in the hex string should have an equivalent four bit binary value). I was advised to use this:

num = "0ff" # (say for eg.)
bin = "%0#{num.size*4}b" % num.hex.to_i

This gives me the correct output 000011111111. I am confused with how this works, especially %0#{num.size*4}b. Could someone help me with this?

like image 904
sundar Avatar asked May 12 '11 11:05

sundar


People also ask

How do you convert a hexadecimal number into binary?

Hexadecimal to binarySplit the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.

How many binary digits are represented by one hexadecimal digit?

Each hexadecimal digit represents four bits (binary digits), also known as a nibble (or nybble). For example, an 8-bit byte can have values ranging from 00000000 to 11111111 in binary form, which can be conveniently represented as 00 to FF in hexadecimal.


2 Answers

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.

like image 144
sawa Avatar answered Oct 12 '22 23:10

sawa


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

like image 25
Michael Kohl Avatar answered Oct 13 '22 00:10

Michael Kohl