liveBook · Manning

Word8

As explained in Learn Haskell by Example

Word8 is Haskell's unsigned 8-bit integer type, representing values from 0 through 255.

Word8 is Haskell’s unsigned 8-bit integer type, representing byte values from 0 through 255. It is a natural fit for binary input: an Attoparsec parser can read one input byte as a Word8 with `anyWord8`. section 12.2.1 section 12.2.3

Use `anyWord8 :: Parser Word8` when a file format stores a value in one byte. For character-oriented parsing, Attoparsec’s `ByteString.Char8` module instead provides helpers for ASCII letters and digits. section 12.2.1

A Word8 cannot hold a 16-bit value by itself. To construct a `Word16` from two consecutive bytes, convert each byte with `fromIntegral`, shift the first converted value left eight places, then combine the values with bitwise OR. section 12.2.3

Combining two bytes

Shifting `1 :: Word8` left by eight yields `0`, because the result still has only eight bits. Converting it first changes the result: `shift (fromIntegral byte1 :: Word16) 8 .|. fromIntegral byte2` produces `257` when both bytes are `1`. section 12.2.3

Listing 12.25 Parser for 16-bit words
import Data.Bits

...

anyWord16 :: Parser Word16
anyWord16 = do
  h <- fromIntegral <$> anyWord8    #1
  l <- fromIntegral <$> anyWord8    #1
  return $ shift h 8 .|. l         #2

This parser reads two `Word8` values, promotes them to `Word16`, and joins them into one big-endian 16-bit word. section 12.2.3

Binary PNM pixel parsers choose the word size that matches the format variant. An 8-bit gray pixel reads one byte and converts it to the pixel representation; an RGB pixel reads three such bytes. Bitmap parsing can also inspect individual bits of a single Word8. section 12.2.3

How Learn Haskell by Example covers it

How deep it goes
Works through promoting two Word8 values into Word16 with shifts and bitwise OR, including an implementation of `anyWord16`.
Examples
Demonstrates shifted Word8 and Word16 values, a two-byte `anyWord16` parser, 8-bit pixel parsers, and bitmap bit extraction.
What you can do after
Apply it via Attoparsec’s `anyWord8` to parse byte-oriented PNM values and assemble larger words when needed.
How it connects
Connects Word8 to Attoparsec, ByteString, Word16, `fromIntegral`, `Data.Bits`, shifts, bitwise OR, and binary PNM parsing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.