Created
February 2, 2017 23:47
-
-
Save JoshuaGross/313bfa6f0de5413eeb2d87c21024f6c9 to your computer and use it in GitHub Desktop.
Use Haskell to display a ByteString as hex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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
commented
Feb 8, 2019
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?
{-# 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