如何在 hbase shell (JRuby) 中将十六进制数字字符串转换为具有十六进制字节转义的字符串

How to convert string of hex digits to string wtih hexdecimal byte escapes in hbase shell (JRuby)

我有 JRuby(实际上是 Apache HBase shell)。 我有很多代表字节的字符串,每个字符都是十六进制数字,每个字节 2 个字符。类似于:

id = "faed31"

但我需要一串转义字符:

=> "\xfa\xed1"

有解决办法吗?未能 google 并且对 Ruby 只有非常一般的印象。

这是实际解决我所有任务的代码,包括需要的输出:

# Convert binary string to hex digits.
def bin_to_hex(s)
  s.each_byte.map { |b| b.to_s(16).rjust(2, '0') }.join
end

# Convers hex string to binary string.
def hex_to_bin(s)
  s.scan(/../).map { |x| x.hex.chr }.join
end

# HBase special 'convert and print' routine to get hex digits, process them and print.
def print_hex_to_bin(s)
  Kernel.print "\"" + Bytes.toStringBinary(s.scan(/../).map { |x| x.hex.chr }.join.to_java_bytes) + "\"\n"
end

主要基于http://anthonylewis.com/2011/02/09/to-hex-and-back-with-ruby/

组成