Skip to content

Instantly share code, notes, and snippets.

@dmke
Last active August 29, 2015 14:15
Show Gist options
  • Save dmke/62df61ef3d6f1c6f497f to your computer and use it in GitHub Desktop.
Save dmke/62df61ef3d6f1c6f497f to your computer and use it in GitHub Desktop.
Hexdump in Ruby
random_twitter_message = (1..140).map{ rand 0xFF }.pack("C*")
hexdump random_twitter_message
# 0000: af 98 02 2b 25 13 01 42 b8 cd 3a a5 23 07 c2 43 |...+%..B ..:.#..C|
# 0010: c0 af bd 65 3e a7 c0 4c 26 b9 1e 54 cc c3 5b 3f |...e>..L &..T..[?|
# 0020: db d6 86 76 22 d4 31 ab 32 fe b6 32 f4 d4 1c 01 |...v".1. 2..2....|
# 0030: f6 5d 25 8c 64 9b 18 3a 9d 50 14 a2 86 79 a6 f2 |.]%.d..: .P...y..|
# 0040: da 50 f3 70 b6 bc e4 76 15 db 2f b7 f6 9c 88 d0 |.P.p...v ../.....|
# 0050: 63 95 23 66 b3 20 f6 ab 62 a6 28 92 c7 6d a9 e0 |c.#f. .. b.(..m..|
# 0060: 1c 2d fe 12 3e fd 8b 95 47 4d b2 14 07 e8 6b 6c |.-..>... GM....kl|
# 0070: 35 7c ef f3 4a 83 af 9a cc 0b ce a1 41 c2 f7 b9 |5|..J... ....A...|
# 0080: 2a 6a 85 3e cc e3 a5 9a f7 dd 2f 17 |*j.>.... ../. |
hexdump random_twitter_message, width: 8
# 0000: 04 bf 68 fe de b8 31 8c |..h. ..1.|
# 0008: 09 e7 31 4e e6 20 33 78 |..1N . 3x|
# 0010: c2 60 2c ee 97 27 4d 15 |.`,. .'M.|
# 0018: 4d 47 d6 ae b0 ef 73 3a |MG.. ..s:|
# 0020: da a5 22 0d 18 12 fb f4 |..". ....|
# 0028: ca 64 4e 43 9c c0 6e 0f |.dNC ..n.|
# 0030: 47 af 5d cd fe 66 1d 76 |G.]. .f.v|
# 0038: 21 1f 69 a9 6d 56 e4 88 |!.i. mV..|
# 0040: 66 5a 94 4a 25 fc 69 84 |fZ.J %.i.|
# 0048: 77 39 d7 6a 54 42 4e 49 |w9.j TBNI|
# 0050: 77 fb e5 63 ed ef 1b bf |w..c ....|
# 0058: f5 ec 78 98 b8 f5 4b 32 |..x. ..K2|
# 0060: 47 63 2f f0 3e bb 54 2c |Gc/. >.T,|
# 0068: 11 1c 5b ec ee e7 51 83 |..[. ..Q.|
# 0070: 1a 02 13 74 44 70 68 ec |...t Dph.|
# 0078: 58 71 e7 fb 2a ab 12 aa |Xq.. *...|
# 0080: df b1 93 ed d3 fa 26 74 |.... ..&t|
# 0088: d3 b7 2b 75 |..+u |
def hexdump(str, width: 16)
bytes = str.unpack("C*")
w = width/2
i = 0
while bytes.size > 0
a, b = bytes.shift(w), bytes.shift(w)
h = [a,b].map {|col| col.map{|c| "%02x" % c }.join(" ") }
c = [a,b].map {|col| col.map{|c| c < 0x20 || c > 0x7E ? '.' : c.chr }.join('') }
mis = (width - a.size - b.size)
case mis
when 1...w
h[1] << (" "*mis)
c[1] << (" "*mis)
when w...width
h[0] << " " << (" "*(mis-1))
c[0] << (" "*mis)
end
puts "%04x: %s %s |%s %s|" % [i, *h, *c]
i += width
end
str
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment