2014-10-30 107 views
0

我想使用紅寶石將十六進制字符串轉換爲字節數組。十六進制字符串到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 ...]

任何建議上做到這一點的最佳方法?

這是我寫到目前爲止,但沒有那麼多快樂的繼續深入,不知道有可能是一個更簡單的方法

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

的ByteArray =十六進制.bytes – rejin 2014-10-30 06:30:22

回答

1
"48656c6c6f2c20576f726c6421".to_i(16).to_s(2) 
#=> "1001000011001010110110001101100011011110010110000100000010101110110111101110010011011000110010000100001" 
+0

我試過這個,但這裏的鏈接顯示不同的值(48656c6c6f2c20576f726c6421)16 =(01001000011001010110110001101100011011110010110000100000010101110110111101110010011011000110010000100001)2:http://www.binaryhexconverter.com/hex-to-binary-converter – victorvasu 2014-10-30 16:54:03

+0

他們看起來和我一樣,除非你提到填充0。 – sawa 2014-10-30 17:04:41

+0

明白了,所以如果長度是奇數,那麼他們填零 – victorvasu 2014-11-02 18:13:47

相關問題