如何将ByteString转换为Int?
我有以下要转换的4个字节(它表示.bmp文件的字节大小):
"v\SOH\NUL\NUL"
我知道等于374
答案 0 :(得分:3)
对于二进制解析,请查看binary
包 - http://hackage.haskell.org/package/binary
它定义了一个Get
monad,所以你可以这样写:
data Header { ftype :: ByteString, size_ :: Word32, reserved_ :: ByteString, offset_ :: Word32 }
parseHeader = do
ft <- getByteString 2
size <- getWord32le
reserved <- getByteString 4
offset <- getWord32le
return $ Header ft size reserved offset
以后:
main = do
bytes <- hGetContents handle
let header = runGet parseHeader bytes
...
答案 1 :(得分:0)
我设法让一个小功能工作,演示了这个想法
import qualified Data.ByteString.Lazy.Char8 as B
lEBsToInt :: B.ByteString -> Int -- littleEndianByteStringToInt
lEBsToInt bs = let bsI = B.take 4 bs in -- 1.
fst $ B.foldl (\(s,i) b -> let shiftBy = i * 8 in -- 2.
(s + (ord b `shiftL` shiftBy), i + 1)) (0,0) bsI --3.
lEBsToInt "v\SOH\NUL\NUL" = 374
这肯定可以改善,但我很满意