Numeric and Binary Data

Check Specific Bit

How would I check if a specific bit is set (equal to 1) within a uint8_t variable?

Abstract art representing computer programming

To check if a specific bit is set in a uint8_t variable, you can use a combination of a bit mask and the bitwise AND operator (&). A bit mask is a value where only the bit you're interested in is set to 1, and all other bits are 0.

Creating a Bit Mask

First, you need to create a bit mask that corresponds to the position of the bit you want to check. You can create this mask by left-shifting the value 1 by the position of the bit you're interested in. Remember that bit positions are counted from right to left, starting at 0.

For example, if you want to check the 3rd bit (which has a position of 2, because we start counting from 0), you would create a mask like this:

#include <cstdint>

int main() {
  uint8_t Mask{1 << 2}; // 0b00000100
}

Using the Bit Mask

Next, you perform a bitwise AND operation between your uint8_t variable and the mask. If the result is non-zero, it means the bit is set. If the result is zero, the bit is not set.

Here's a complete example:

#include <cstdint>
#include <iostream>

int main() {
  uint8_t MyByte{0b01001010};

  // Check the 6th bit (position 5)
  uint8_t Mask{1 << 5};

  if ((MyByte & Mask) != 0) {
    std::cout << "Bit is set\n";
  } else {
    std::cout << "Bit is not set\n";
  }
}
Bit is not set

How The Example Works

In this code, MyByte & Mask will be 0b00001000 if the 6th bit of MyByte is 1, and 0b00000000 otherwise. The if statement checks if the result is non-zero to determine whether the bit is set.

This technique is fundamental for many low-level programming tasks, such as configuring hardware registers, working with bit flags, or manipulating packed data structures.

By using bit masks and bitwise operations, you can efficiently test and modify individual bits within a larger data unit.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 79 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved