在Haskell中在Word8和Word16之间进行转换

时间:2014-05-01 16:58:06

标签: haskell type-conversion

我试图在haskell中进行小端转换,这样我就可以将Word16转换为两个Word8(例如258 = 1 * 256 + 2,因此结果应为[2,1])。然后我将结果打包成ByteString。

我为此目的创建了以下代码:

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

函数getByte从数字b获取字节数num。函数encodeWord16使用此辅助函数进行小端转换。

然而这不能编译,我收到错误:

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

我(非常不系统地)尝试通过随机分发fromIntegral表达式来实现所需的结果,但显然我对haskell类型系统的理解不足以解决这个问题。有没有系统的方法来解决这个问题? 基本上我希望函数encodeWord16具有类型签名Word16 -> [Word8]

4 个答案:

答案 0 :(得分:7)

fromIntegral可用于各种整数类型之间的转换。

fromIntegral :: (Num b, Integral a) => a -> b

encodeWord16 :: Word16 -> [Word8]
encodeWord16 x = map fromIntegral [getByte 1 x, getByte 2 x]

getByte返回Word8 - s会更好:

getByte :: Int -> Word16 -> Word8
getByte b num = fromIntegral $ shift (relevantBits b num) (shiftNum b)
    -- where ...

答案 1 :(得分:3)

您可能希望使用预定义的函数来执行此操作,而不是手动编码转换。

import Data.Word
import Data.ByteString.Builder
import Data.ByteString.Lazy (unpack)

encodeWord16 :: Word16 -> [Word8]
encodeWord16 = unpack . toLazyByteString . word16LE

答案 2 :(得分:2)

如何直接提取这些字节?像这样:

encodeWord16 x = [ x .&. 0xFF, (x .&. 0xFF00) `shiftR` 8 ]

如果您希望encodeWord16的签名为Word16 -> [Word8],请在其前面添加map fromIntegral,如下所示:

encodeWord16 :: Word16 -> [Word8]
encodeWord16 x = map fromIntegral [ x .&. 0xFF, (x .&. 0xFF00) `shiftR` 8 ]

答案 3 :(得分:1)

binary包含以下代码:

-- Words16s are written as 2 bytes in big-endian (network) order
instance Binary Word16 where
    put     = putWord16be

http://hackage.haskell.org/package/binary-0.7.1.0/docs/Data-Binary.html#g:1

-- | Write a Word16 in big endian format
putWord16be :: Word16 -> Builder
putWord16be w = writeN 2 $ \p -> do
    poke p               (fromIntegral (shiftr_w16 w 8) :: Word8)
    poke (p `plusPtr` 1) (fromIntegral (w)              :: Word8)

http://hackage.haskell.org/package/binary-0.7.1.0/docs/Data-Binary-Builder.html#g:5

所以你可以像这样使用它:

> encode (355 :: Word16)
"\SOHc"
> toLazyByteString $ putWord16be 355
"\SOHc"
> index (encode (355 :: Word16)) 0
1
> index (toLazyByteString $ putWord16be 355) 0
1
> index (encode (355 :: Word16)) 1
99
> index (toLazyByteString $ putWord16be 355) 1
99