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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With