Skip to content

Instantly share code, notes, and snippets.

@pib
Created October 16, 2010 01:01
Show Gist options
  • Save pib/629245 to your computer and use it in GitHub Desktop.
Save pib/629245 to your computer and use it in GitHub Desktop.
hexdump in Haskell
import Data.Char
import System.IO
import Text.Printf
main = do
hSetBinaryMode stdin True
contents <- getContents
putStr (hexdump contents)
hexdump :: String -> String
hexdump contents =
let chunks = chunkify 8 contents
hexchunks = map hexify chunks
pchunks = map (\chunk -> map (\c -> if (isAscii c && c /= '\n') then c else '.') chunk) chunks
dump = map (\(h, p) -> printf "%-24s %s" h p) (zip hexchunks pchunks)
in unlines dump
chunkify :: Int -> [a] -> [[a]]
chunkify _ [] = []
chunkify chunksize l = chunk : chunkify chunksize rest
where (chunk, rest) = splitAt chunksize l
hexify :: String -> String
hexify = unwords . map (printf "%02x" . ord :: Char -> String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment