Skip to content

Instantly share code, notes, and snippets.

@JoshuaGross
Created February 2, 2017 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaGross/313bfa6f0de5413eeb2d87c21024f6c9 to your computer and use it in GitHub Desktop.
Save JoshuaGross/313bfa6f0de5413eeb2d87c21024f6c9 to your computer and use it in GitHub Desktop.
Use Haskell to display a ByteString as hex
-- can be used in ghci
import qualified Data.ByteString as B
import Numeric (showHex)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Binary as B
-- encode some object to a binary ByteString
let s = (B.encode someObjectThatHasBinaryInstance)
let prettyPrint = P.concatMap ((\x -> "0x"++x++" ") . flip showHex "") . B.unpack :: B.ByteString -> String
prettyPrint (LBS.toStrict s)
@codemonkeylabs-de
Copy link

prettyPrint :: ByteString -> String
prettyPrint = B.foldr showHex ""

@jhelovuo
Copy link

original example:

GHCi> prettyPrint "ab\0"
"0x61 0x62 0x0 "

1st comment code:

GHCi> prettyPrint "ab\0"
"61620"

I would have expected "616200". Maybe 0-padding to two hex digits is missing?

@jhelovuo
Copy link

{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import Data.Text (Text)
import Text.Printf
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as B

toHexString :: ByteString -> Text
toHexString = B.foldr (\b -> (<>) (T.pack $ printf "%02x" b)) ""

This one seemed to work for me, but requires Printf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment