Search code examples
stringshellhbasejruby

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


I have JRuby (actually Apache HBase shell). I have lot of strings which represent bytes, every character is hex digit, 2 chars per byte. Something like:

id = "faed31"

But I need string of escaped characters:

=> "\xfa\xed1"

Any solution? Failed to google and have only very general impression about Ruby.


Solution

  • Here is the code which actually solves all my tasks including output that was wanted:

    # 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
    

    Composed mostly based on http://anthonylewis.com/2011/02/09/to-hex-and-back-with-ruby/