假设我有以下类型:
data WaveFormatChunk = WaveFormatChunk {
compression :: Word16,
channels :: Word16,
sampleRate :: Word32,
averageBps :: Word32,
blockAlign :: Word16,
significantBits :: Word16
} deriving (Show)
有没有办法将所有这些全部转储到 ByteString (或类似的结构)中(以一种古老的 C 结构的方式)?如果没有,我必须编写一个将所有这些单独放入列表的函数,是否至少有函数可以轻松地将值粘贴到 Word8 列表中?类似于 putWordBBxe 的东西,除了字节字符串或列表(尽管我很可能犯了严重错误,因为我还没有正确地读入 Monads,在我看来,Get/Put 主要用于流)。
Data.Binary 并不是我正在寻找的,它似乎只是将数据转储到光盘上而不是将其存储在具有特定(和“错误”)字节序的特定格式中更有用。
最佳答案
Data.Binary将让您将结构序列化为字节串,显式使用 little-endian operators .
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# LANGUAGE RecordWildCards #-}
import Data.Binary
import Data.Binary.Put
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy as L
data WaveFormatChunk =
WaveFormatChunk {
compression :: !Word16,
channels :: !Word16,
sampleRate :: !Word32,
averageBps :: !Word32,
blockAlign :: !Word16,
significantBits :: !Word16
}
instance Binary WaveFormatChunk where
put (WaveFormatChunk{..}) = do
putWord16le compression
putWord16le channels
putWord32le sampleRate
putWord32le averageBps
putWord16le blockAlign
putWord16le significantBits
get = undefined
main = C.putStr $ C.concat $ L.toChunks $ encode test
where
test = WaveFormatChunk {
compression = 0xcafe
, channels = 0xface
, sampleRate = 0xdeadbeef
, averageBps = 0xf01dab1e
, blockAlign = 0x5566
, significantBits = 0xb01d
}
将产生:
$ ./A | od -x
0000000 cafe face beef dead ab1e f01d 5566 b01d
因此,您可以对表示进行精确的字节级控制。如果您对流式传输不感兴趣,您也可以从麦片包装中获得相同的效果。
关于haskell - 如何轻松地序列化小端 POD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14920566/