Skip to content

Instantly share code, notes, and snippets.

@m0smith
Created January 26, 2012 19:16
Show Gist options
  • Save m0smith/1684476 to your computer and use it in GitHub Desktop.
Save m0smith/1684476 to your computer and use it in GitHub Desktop.
Perform similar to hexlify in emacs. Accept a seq of bytes and convert it into a seq of vectors. The first element of the vector is a seq of 16 strings for the HEX value of each byte. The second element of the vector is a seq of the printable represent
(defprotocol Hexl
(hexl-hex [val])
(hexl-char [char]))
(extend-type Number
Hexl
(hexl-hex [i]
(let [rtnval (Integer/toHexString (if (< i 0) (+ 256 i) i)) ]
(if (< (count rtnval) 2) (str "0" rtnval) rtnval)))
(hexl-char [b]
(let [v (if (< b 0) (+ 256 b) b)
c (char v)]
(if (and (< v 128 )(Character/isLetter c)) (.toString c) "."))))
(extend-type Character
Hexl
(hexl-hex [char]
(hexl-hex (int (.charValue char))))
(hexl-char [char]
(hexl-char (int (.charValue char)))))
(defn hexlify
"Perform similar to hexlify in emacs. Accept a seq of bytes and
convert it into a seq of vectors. The first element of the vector is a
seq of 16 strings for the HEX value of each byte. The second element
of the vector is a seq of the printable representation of the byte and the
third elevment of thee vector is a seq of the integer value for each
byte. Works for chars as well."
([bytes] (hexlify bytes 16))
([bytes size]
(let [parts (partition-all size bytes)]
(for [part parts]
[ (map hexl-hex part) (map hexl-char part) (map int part)]))))
(defn hexlify-chars
"Convert the bytes into a string of printable chars
with . being used for unprintable chars"
[bytes]
(let [chars (mapcat second (hexlify bytes))]
(apply str chars)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment