Below are some common conversions I've needed in the past:
#Convert Hex number to Ascii:
> "\x41"
=> "A"
#Convert cat'd hex to ascii:
> 414142444534.to_s.split.pack("H*")
=> "AABDE4"
#Convert ascii "A" to Hex:
"A".unpack("H*")
=> ["41"]
#Convert ascii "A" to Decimal number
> "A".ord
=> 65
#Convert ascii 'asdf' to Decimal numbers
> 'asdf'.chars.map(&:ord)
=> [97, 115, 100, 102]
#or
> 'asdf'.chars.map {|x| x.ord}
=> [97, 115, 100, 102]
#Convert "AAAA" to \x41\x41\x41\x41
> puts "AAAA".unpack("H*")[0].chars.each_slice(2).map{ |a, b| "\\x#{a}#{b}" }.join
\x41\x41\x41\x41
=> nil
#or
> puts "ABCD".unpack('H*')[0].gsub(/(..)/,'\x\1')
\x41\x42\x43\x44
=> nil
No comments:
Post a Comment