我正在使用来自 Data.Binary 的获取 monad,从包含带符号16位整数的二进制文件中读取结构。我目前的代码如下:
data DetectorStats = DetectorStats Int16 Word8 Word8
Word8 Int16 Version Int16
deriving Show
getDetectorStats :: Get DetectorStats
getDetectorStats = do
productNumber <- getWord16be
bitPerCoordinate <- getWord8
energyCapability <- getWord8
timingCapability <- getWord8
clockFrequency <- getWord16be
serialNumber <- getWord16be
return (DetectorStats (unsafeCoerce productNumber )
bitPerCoordinate
energyCapability
timingCapability
(unsafeCoerce clockFrequency)
firmwareVersion
(unsafeCoerce serialNumber))
我对使用 unsafeCoerce 感到不满意,但似乎没有办法直接读取 Int16 ,也没有办法转换 Word16 进入 Int16 。有没有更好的方法来处理这个?
答案 0 :(得分:8)
fromIntegral 会将Word16转换为Int16。但是,您必须检查它是否得到了您预期的签名结果。
答案 1 :(得分:3)
答案 2 :(得分:1)
在Stephen的答案的基础上,这是一个实现Int8,Int16和Int32的get和put函数,类似于Word8,Word16和Word32的现有函数。我还没有要求Int64
或Host-endian支持,但可以添加这些:
{-# LANGUAGE RecordWildCards #-}
module GetAndPutForInt
( getInt8
, getInt16be
, getInt16le
, getInt32be
, getInt32le
, putInt8
, putInt16be
, putInt16le
, putInt32be
, putInt32le
) where
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.Int
import Data.Word
import qualified Data.ByteString.Lazy as B
getInt8 :: Get Int8
getInt8 = do a <- getWord8
return $ fromIntegral a
getInt16be :: Get Int16
getInt16be = do a <- getWord16be
return $ fromIntegral a
getInt16le :: Get Int16
getInt16le = do a <- getWord16le
return $ fromIntegral a
getInt32be :: Get Int32
getInt32be = do a <- getWord32be
return $ fromIntegral a
getInt32le :: Get Int32
getInt32le = do a <- getWord32le
return $ fromIntegral a
putInt8 :: Int8 -> Put
putInt8 i = putWord8 ((fromIntegral i) :: Word8)
putInt16be :: Int16 -> Put
putInt16be i = putWord16be ((fromIntegral i) :: Word16)
putInt16le :: Int16 -> Put
putInt16le i = putWord16le ((fromIntegral i) :: Word16)
putInt32be :: Int32 -> Put
putInt32be i = putWord32be ((fromIntegral i) :: Word32)
putInt32le :: Int32 -> Put
putInt32le i = putWord32le ((fromIntegral i) :: Word32)
data TestType = TestType
{ a :: Int16
, b :: Int16
} deriving (Show, Eq)
instance Binary TestType where
put TestType{..} =
do putInt16be a
putInt16le b
get = do a <- getInt16be
b <- getInt16le
return TestType{..}
main :: IO ()
main = do
putStrLn "Supplies Get and Put support to Int8, Int16 etc. types as Data.Binary.Get and Data.Binary.Push do for Word8, Word 16 etc."
putStrLn ""
putStrLn "Test data in bytes:"
print bytes
putStrLn ""
putStrLn "As TestType:"
print (decode bytes :: TestType)
putStrLn ""
putStrLn "Back to bytes:"
print $ (encode ((decode bytes) :: TestType))
where
bytes = B.pack $ concat $ replicate 2 [0xCD,0xEF]