我正在尝试在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
从数字num
中获取第b
个字节。函数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]
。
map fromIntegral
(请参见András Kovács的答案)。 - Julianx
的类型是Word16
,那么x .&. 0xFF
的类型也将是Word16
。 - Lee Duhem