1

I am trying to convert a hex string into byte array using ruby.

48656c6c6f2c20576f726c6421 => 0100 1000 0110 0101 0110 1100 0110 1100 0110 1111 0010 1100 0010 0000 0101 0111 0110 1111 0111 0010 0110 1100 0110 0100 0010 0001 => [72, 65...]

Any suggestions on the best approach to do this?

This is what i have written till now but not that much happy to continue further, wondering there could be a much easier way

binaryArray = Array.new

            hex.each_char do |x|
                     bin = x.hex.to_s(2) #get the binary value for the HEX
                     val = bin.rjust(4,'0') # padding with zeros to have a 4 digits
                     binaryArray.push(val)
            end
1
  • 1
    byteArray = hex.bytes Commented Oct 30, 2014 at 6:30

1 Answer 1

1
"48656c6c6f2c20576f726c6421".to_i(16).to_s(2)
#=> "1001000011001010110110001101100011011110010110000100000010101110110111101110010011011000110010000100001"
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried this, but the link here shows a different value (48656c6c6f2c20576f726c6421)16 = (01001000011001010110110001101100011011110010110000100000010101110110111101110010011011000110010000100001)2 : binaryhexconverter.com/hex-to-binary-converter
They look the same to me unless you are mentioning the padded 0.
Got it, so if the length is odd number then they pad a zero

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.