Skip to content
BoKSA

Bit Operations in C

Bit Operations in C

Introduction

A microcontroller register is a row of bits. One bit turns an LED on, another starts a timer, another reports that a sensor line is high. Bit operations let you change one of those bits and leave the rest alone.

You already know that integers are binary patterns (Data representation). This article is how you set, clear, toggle, and test a single bit, and how a mask selects which bits you mean. Hardware headers are full of these patterns. The macros in C types and macros (BIT, SET_BIT, CLEAR_BIT) are the same idea with a shorter name.


A bit inside an integer

Number the bits from the right, starting at 0. Bit 0 is worth 1, bit 1 is worth 2, bit 3 is worth 8.

1
2
3
4
bit:    7   6   5   4   3   2   1   0
value: 128  64  32  16   8   4   2   1

example: 0b00001010  =  8 + 2  =  10

0b00001010 and 0x0A and 10 are the same value. Hex is the usual way to write a mask in firmware because each hex digit is exactly four bits.


The six bitwise operators

Operator Name What a 1 in the result means
& AND Both bits were 1
| OR At least one bit was 1
^ XOR The two bits differed
~ NOT The bit was flipped
<< Left shift Bits moved toward the high end
>> Right shift Bits moved toward the low end
1
2
3
4
  1100          1100          1100
& 1010        | 1010        ^ 1010
  ----          ----          ----
  1000          1110          0110

So 12 & 10 is 8, 12 | 10 is 14, and 12 ^ 10 is 6.

& and | are bitwise. && and || are logical: they only care whether a whole value is zero or not. value & 0x08 tests a bit. value && 0x08 only asks "are both numbers non-zero?" and throws the bit pattern away.

In plain terms

A mask is a stencil. You hold it over the integer and the holes show the bits you care about. AND keeps those bits. OR punches a 1 through a hole. XOR flips whatever is under a hole.


Building a mask with a shift

1u << n is a value with only bit n set.

Expression Bits Decimal
1u << 0 00000001 1
1u << 1 00000010 2
1u << 3 00001000 8

The u makes the 1 unsigned. Bit work on a signed int gets awkward: right-shifting a negative value is implementation-defined, and ~ flips every bit of a promoted int, including bits you did not mean to touch. Prefer uint8_t, uint16_t, or uint32_t from <stdint.h> for registers and flags.


Set, clear, toggle, and test

These four lines are the ones you will type most often. n is the bit number.

Set (force the bit to 1)

1
value |= (1u << n);

OR with a 1 turns that bit on and leaves every other bit as it was.

1
2
3
4
  00000010
| 00001000     set bit 3
  --------
  00001010

Clear (force the bit to 0)

1
value &= ~(1u << n);

~(1u << 3) is a mask of all ones except bit 3. AND with that mask clears bit 3 and keeps the rest.

1
2
3
4
  00001010
& 11110111     clear bit 3
  --------
  00000010

Toggle (flip the bit)

1
value ^= (1u << n);

XOR with 1 flips that bit. A second toggle puts it back.

Test (read the bit)

1
2
3
if (value & (1u << n)) {
    /* bit n is 1 */
}

The result is zero when the bit is clear, and non-zero when it is set. Compare with an explicit mask when you need "these bits, exactly":

1
2
3
if ((value & mask) == mask) {
    /* every bit in mask is set */
}

Parentheses matter. & binds less tightly than ==, so write (value & mask) == 0, not value & mask == 0.


Several flags in one integer

A status byte can hold many yes/no facts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#define FLAG_ENABLED  (1u << 0)
#define FLAG_DEBUG    (1u << 1)
#define FLAG_LOGGING  (1u << 2)

uint32_t flags = 0;

flags |= FLAG_ENABLED;
flags |= FLAG_DEBUG;

if (flags & FLAG_DEBUG) {
    /* debug is on */
}

flags &= ~FLAG_DEBUG;   /* debug off */
flags ^= FLAG_LOGGING;  /* logging flips */

One integer, many settings. Peripheral headers do the same thing with names from the datasheet (USART_CR1_UE, GPIO_MODER_MODE5, and so on).


Reading a group of bits

A field is several neighbouring bits, not just one. Mask them, then shift the group down to bit 0.

Bits 2–4 of value sit under the mask 0x38 (0b00111000). Shifting right by 2 moves that group to the bottom:

1
uint32_t field = (value & 0x38u) >> 2;
1
2
3
4
5
6
  11010110
& 00111000
  --------
  00010000
>> 2
  00000100     field = 4

The lowest four bits are the same idea with a simpler mask: value & 0x0Fu.


On a hardware register

Writing a GPIO or timer register is the same pattern. The address comes from the reference manual. volatile tells the compiler the hardware can change the value behind your back. See Pointers in C.

1
2
3
4
volatile uint32_t *odr = (uint32_t *)0x40020014;

*odr |=  (1u << 5);   /* pin 5 on  */
*odr &= ~(1u << 5);   /* pin 5 off */

Read-modify-write (|=, &=) updates one bit in a copy of the register and writes the whole word back. On some peripherals a write of 1 to a bit already means "clear this flag" or "set only". Check the register description before you invent a mask. Vendor SET_BIT / CLEAR_BIT macros exist so the whole team uses one spelling.


Relevant topics


Starting points

  1. Write uint8_t value = 0x0A and set, clear, toggle, and test bit 3. Print the value in hex after each step and check it by hand.
  2. Pack three flags into one uint8_t with #define masks, then turn one flag off without touching the others.
  3. Find SET_BIT or |= (1U << in your MCU header or a lab project and name the register it changes.
  4. Break precedence on purpose: compare if (value & mask == 0) with if ((value & mask) == 0) and see which one the compiler warns about.

Focus points

  • Use unsigned types (uint32_t, 1u << n) for masks and shifts.
  • Parenthesize masks inside if: (value & mask).
  • Do not shift by the width of the type or more. 1u << 32 on a 32-bit unsigned is not a portable "bit 32".
  • Read the register chapter before a read-modify-write. Some bits are "write 1 to clear".
  • & is not &&. A bitwise test and a logical test answer different questions.

Key points

  • A mask selects bits. 1u << n selects bit n.
  • Set with |=, clear with &= ~, toggle with ^=, test with &.
  • Unsigned fixed-width types keep bit patterns predictable across laptop and MCU.
  • Peripheral control in C is these four operations with names taken from the datasheet.