I am trying to convert little endian to haskell so that I can turn Word16 into two Word8 (for example, 258 = 1 * 256 + 2, so the result should be [2, 1]). Then I pack the result into a byte string.
I have created the following code for this purpose:
import Data.Word
import Data.Bits
getByte b num = shift (relevantBits b num) (shiftNum b)
where bitMask b = sum $ map (2^) [8*b-8 .. 8*b-1]
relevantBits b num = num .&. bitMask b
shiftNum b = 8-8*b
encodeWord16 x = [getByte 1 x, getByte 2 x]
input :: Word16
input = 355
output :: [Word8]
output = encodeWord16 input
The function getBytegets the number of bytes bfrom a number num. The function encodeWord16uses this helper function to convert the small end.
This, however, does not compile, I get an error:
Couldn't match expected type `Word8' with actual type `Word16'
In the first argument of `encodeWord16', namely `input'
In the expression: encodeWord16 input
In an equation for `output': output = encodeWord16 input
I ( ) fromIntegral, , , haskell . ?
, , encodeWord16 Word16 -> [Word8].