Convert (decode) hexadecimal string to binary stri

2020-02-06 05:30发布

How can I convert "1234567890" to "\x12\x34\x56\x78\x90" in Ruby?

标签: ruby
6条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-06 05:44

Try this:

["1234567890"].pack('H*')
查看更多
迷人小祖宗
3楼-- · 2020-02-06 05:44
(0..4).map { |x| "0x%X" % (("1234567890".to_i(16) >> 8 * x) & 255) }.reverse
查看更多
爷的心禁止访问
4楼-- · 2020-02-06 05:53
class String

  def hex2bin
    s = self
    raise "Not a valid hex string" unless(s =~ /^[\da-fA-F]+$/)
    s = '0' + s if((s.length & 1) != 0)
    s.scan(/../).map{ |b| b.to_i(16) }.pack('C*')
  end

  def bin2hex
    self.unpack('C*').map{ |b| "%02X" % b }.join('')
  end

end
查看更多
可以哭但决不认输i
5楼-- · 2020-02-06 05:55

Ruby 1.8 -

hex_string.to_a.pack('H*')

Ruby 1.9 / Ruby 1.8 -

Array(hex_string).pack('H*')
查看更多
太酷不给撩
6楼-- · 2020-02-06 05:55

Assuming you have a well-formed hexadecimal string (pairs of hex digits), you can pack to binary, or unpack to hex, simply & efficiently, like this:

string = '0123456789ABCDEF'
binary = [string].pack('H*')     # case-insensitive
 => "\x01#Eg\x89\xAB\xCD\xEF"
hex = binary.unpack('H*').first  # emits lowercase
 => "012345679abcdef"
查看更多
别忘想泡老子
7楼-- · 2020-02-06 05:58

If you have a string containing numbers and you want to scan each as a numeric hex byte, I think this is what you want:

"1234567890".scan(/\d\d/).map {|num| Integer("0x#{num}")}
查看更多
登录 后发表回答