How to convert ByteString to Int and deal with content?

I need to read the binary format in Haskell. The format is quite simple: four octets indicating the length of the data, followed by the data. Four octets are an integer in network byte order.

How to convert a ByteString from four bytes to an integer? I want direct composition (in C, which would be *(int*)&data ), and not a lexicographic conversion. Also, how would I go for approval? The serialized integer is in network byte order, but the machine may use a different byte order.

I tried Google, but these are just the results of the lexicographic conversion.

+5
source share
3 answers

The binary package contains tools for obtaining integer types of various sizes and byte orders from ByteStrings.

 λ> :set -XOverloadedStrings λ> import qualified Data.Binary.Get as B λ> B.runGet B.getWord32be "\STX\SOH\SOH\SOH" 33620225 λ> B.runGet B.getWord32be "\STX\SOH\SOH\SOHtrailing characters are ignored" 33620225 λ> B.runGet B.getWord32be "\STX\SOH\SOH" -- remember to use 'catch': *** Exception: Data.Binary.Get.runGet at position 0: not enough bytes CallStack (from HasCallStack): error, called at libraries/binary/src/Data/Binary/Get.hs:351:5 in binary-0.8.5.1:Data.Binary.Get 
+12
source

I assume that you can use the fold and then use either foldl or foldr to determine which end element you want (I forgot what it is).

 foldl :: (a -> Word8 -> a) -> a -> ByteString -> a 

I think this will work for a binary operator:

 foo :: Int -> Word8 -> Int foo prev v = (prev * 256) + v 
+4
source

I would simply extract the first four bytes and combine them into a single 32-bit integer using functions in Data.Bits :

 import qualified Data.ByteString.Char8 as B import Data.Char (chr, ord) import Data.Bits (shift, (.|.)) import Data.Int (Int32) readInt :: B.ByteString -> Int32 readInt bs = (byte 0 `shift` 24) .|. (byte 1 `shift` 16) .|. (byte 2 `shift` 8) .|. byte 3 where byte n = fromIntegral $ ord (bs `B.index` n) sample = B.pack $ map chr [0x01, 0x02, 0x03, 0x04] main = print $ readInt sample -- prints 16909060 
+3
source

Source: https://habr.com/ru/post/975326/


All Articles