Search code examples
haskellpackendianness

Need to decode 16-bit unsigned big-endian bytes into integers in Haskell


Is there a simple function I can copy and paste to make this conversion? The Ruby equivalent would be

bytes.unpack("n*")

Solution

  • Use the cereal or binary package, decode into a 16 bit unsigned int (Word16) then convert that value to a full Integer:

    import Data.Serialize
    ...
    someFunction = ...
        let intVal = runGet (fromIntegral `fmap` getWord16be) bytes
    

    Edit:

    As with any monad in haskell, you can use higher level function such as replciateM along with the above code to get a list of int values (untested code follows):

    import Data.Serialize
    ...
    someFunction = ...
        let intVals = runGet (do n <- get
                                 replicateM n (fromIntegral `fmap` getWord16be)) bs