2

Is it possible to read a 5-byte segment of data into a Word64 using the binary package, leaving the three higher-order bits empty? Or must I use a ByteString?

scopchanov
  • 7,966
  • 10
  • 40
  • 68
xuq01
  • 588
  • 4
  • 17
  • Why the downvote? – xuq01 Oct 26 '18 at 03:56
  • The question is absolutely OK, no need to close. – arrowd Oct 26 '18 at 08:49
  • The question is rather unclear to me. If the five bytes are not a byrestring then how are you wanting to use the binary package? What higher order bites should remain empty? 61 62 63 or 37 38 and 39? – Thomas M. DuBuisson Oct 26 '18 at 14:26
  • Also, what had stopped you from doing this? Usually questions without an attempt are voted close for reasons such as "too broad". – Thomas M. DuBuisson Oct 26 '18 at 14:27
  • @ThomasM.DuBuisson I can use and live with a bytestring, but just wondering if I could do C-style bit-packing with `binary`. – xuq01 Oct 26 '18 at 17:11
  • Ah so as @bergey said we could use Data.Bits or just plain old multiplication such as `toWord64 = foldl (\a c - >a*256 + fromIntegral c) 0 :: [Word8] -> Word64` and bitmasks can be applied as desired to ensure the right bits are zero. If you want to use Binary then the implication is using bytestring, for example you could `decode . (pack [0,0,0] <>) :: ByteString -> Word64`. – Thomas M. DuBuisson Oct 26 '18 at 18:47
  • @ThomasM.DuBuisson I see. So I need to go through a ByteString absolutely, and in my case I'd just use the ByteString itself. The answer to _my_ question is no, then. Thanks! – xuq01 Oct 26 '18 at 19:40

1 Answers1

1

Shift and bitwise-OR are in Data.Bits. Data.Binary.Get has a family of getWord functions that read fixed-length pieces from a ByteString of unknown length, without any interpretation beyond endian-ness. It may also help to know that fromIntegral for Word types preserves the unsigned-int interpretation of the Word (when going from smaller to larger words), so you can zero-extend a Word8 to a Word64.

bergey
  • 3,041
  • 11
  • 17