liveBook · Manning

testBit

As explained in Learn Haskell by Example

testBit is a Haskell bit operation that reports whether a value has a one at a specified bit offset.

testBit :: a -> Int -> Bool checks whether a value has a one at a specified bit offset. For binary bitmap parsing, read a Word8 and test its eight offsets individually. section 12.2.3

Extracting eight bitmap pixels

A bitmap parser defines parseBitAtIndex n = Single $ if testBit w n then 1 else 0, then tests offsets 7 through 0. This returns eight pixel values in most-significant-to-least-significant order. section 12.2.3

Listing 12.27 A parser for binary-encoded bitmaps
p4PixelP ::
  Parser
    ( RawPixel,
      RawPixel,
      RawPixel,
      RawPixel,
      RawPixel,
      RawPixel,
      RawPixel,
      RawPixel
    )
p4PixelP = do
  w <- anyWord8           #1
  let parseBitAtIndex n =
        Single $ if testBit w n then 1 else 0    #2
  return
    ( parseBitAtIndex 7,     #3
      parseBitAtIndex 6,     #3
      parseBitAtIndex 5,     #3
      parseBitAtIndex 4,     #3
      parseBitAtIndex 3,     #3
      parseBitAtIndex 2,     #3
      parseBitAtIndex 1,     #3
      parseBitAtIndex 0      #3
    ) #3

Inspect the complete binary bitmap parser, including the local testBit helper and its eight returned pixel positions. section 12.2.3

How Learn Haskell by Example covers it

How deep it goes
Defines the type and demonstrates repeated offset checks, but defers broader bitwise implementation details.
Examples
Uses one Word8, eight offsets, and a tuple of Single pixel values ordered from offset 7 to offset 0.
What it assumes
Assumes familiarity with Word8 values and binary bitmap parsing while introducing per-bit extraction.
What you can do after
Apply it via Data.Bits to extract individual pixel bits from binary bitmap bytes.
How it connects
Connects testBit with Data.Bits, Word8, binary bitmap parsing, and PNM file formats.

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.