Monday, October 15, 2018

[jhomitso] Haskell pack int to bytes

The following Haskell code demonstrates packing a 32-bit unsigned integer (Word32) into a (lazy) ByteString with big-endian byte ordering, using the Put monad of Data.Binary in the binary package.  Essentially, runPut . putWord32be is the Word32 -> ByteString conversion function.

module Main(main) where {
import qualified Data.Binary.Put;
import Data.Word(Word32);
import qualified Data.ByteString.Lazy;

value :: Word32;
value = 65539; -- 3 + 2^16

main :: IO();
main = out_bytestring $ Data.Binary.Put.runPut $ Data.Binary.Put.putWord32be value;

{- expected output:
0 1 0 3
-}

out_bytestring :: Data.ByteString.Lazy.ByteString -> IO();
out_bytestring = putStrLn . unwords . map show . Data.ByteString.Lazy.unpack;
}

This code is analogous to Perl's pack function.  Here is the mapping from Perl's pack template characters to Haskell functions:

L = putWord32host
N = putWord32be (network, big-endian)
V = putWord32le (x86, vax, little-endian)

To convert from lazy to strict ByteString, do Strict.concat . Lazy.toChunks

No comments :