Beetwise

Bit positions and off-by-one errors

Bit 0 is the rightmost bit, and it holds the value 1.

A datasheet writes a field as [11:10], which means bit 11 down to bit 10.

A field of w bits for item n starts at the position n times w.

Try bit positions in the bit editor

Bit 10, which is the low bit of the field for pin 5. Edit the expression or select a bit to flip it.

15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0x0400
hex · 16 bits
value
1024
Bit width

Bit positions step by step

Find the bits of pin 5 in a register with two bits per pin:

  1. The field width is 2, so multiply: 5 times 2 gives 10.
  2. The field of pin 5 is the bits 11 and 10.
  3. The mask for the field is 3 << 10, which is 0x0C00.
  4. The mask for the low bit alone is 1 << 10, which is 0x0400.

Where the field of each item starts

Where the field of each item starts
Field widthItem 0Item 5Item n
1 bitbit 0bit 5bit n
2 bitsbits 1:0bits 11:10bits 2n+1 : 2n
4 bitsbits 3:0bits 23:20bits 4n+3 : 4n
8 bitsbits 7:0bits 47:40bits 8n+7 : 8n

Where bit positions is used

A GPIO mode register holds two bits per pin, so the position is twice the pin number.

An alternate function register holds four bits per pin, and it splits across two registers.

A DMA or interrupt priority register packs a field of four or eight bits per channel.

Bit positions: points to note

  • Bit 0 is the first bit, not bit 1. A count that starts at 1 shifts every mask by one position.
  • The notation [11:10] names the high bit first. The mask starts at the lower number.
  • A field of 4 bits per pin runs past 16 bits. Pins 8 and above live in a second register.
  • The leftmost bit on screen is the highest, not bit 0. The editor above numbers each cell.

The full bit editor

The full editor holds many values, evaluates expressions across them, and reads live values from a serial port.

Open this value in the full editor

Questions about bit positions

Which bit is bit 0?
The rightmost bit, which holds the value 1. Bit numbers count from 0 upward, to the left.
What does [11:10] mean?
A field of two bits, from bit 11 down to bit 10. The mask is 3 shifted left by 10.
Why is pin 5 at bit 10?
The register holds two bits for each pin, so the field of pin n starts at 2n.