C++ Bitwise Operations Basics: Bit Extraction and Flag Setting

In practical C++ development, bit operations are a common technique, especially when dealing with system states, flags, or control bits. Bit operations can provide very efficient solutions. This article will explain how to use bit operations to get and set specific flag bits through an example.

Basic operating concepts

In computers, data is stored in binary digits (bits) of 0 and 1. Bitwise operations are operations performed on these binary digits. C++ has several commonly used bitwise operators:

  • Bitwise AND (&): Used to check if a bit is 1
  • Bitwise OR (|): Used to set a bit to 1
  • XOR (exclusive OR) by bit: Used to invert a specific bit
  • Bitwise NOT (~) : Inverts all bits
  • Shift all bits left by several positions
  • Shifts all bits to the right by several positions

In this example, we need to perform a series of bit operations on an unsigned short type variable wInfo, using different flag bits to represent different states

flowchart LR
    A[原始数值: 00010000] --> B[左移: 00010000 << 1]
    B --> C[结果: 00100000]
    C --> D[右移: 00100000 >> 1]
    D --> E[结果: 00010000]

    subgraph 左移操作
        direction LR
        A --> B --> C
    end

    subgraph 右移操作
        direction LR
        C --> D --> E
    end

Requirements Analysis

According to the description in the question, we have a 16-bit flag used to represent different states. These states are represented by various binary bits, each corresponding to a specific meaning. For example:

  • Has bit0 failed?
  • Is bit1 compressed?
  • Is bit2 incremental?
  • Does bit3 have any follow-up packages?
  • Normal request or logout

Implement using bit operations

We will use bit operations to set and get these flag bits. Specifically:

  • Extracting bit values: Obtain the value of a specific bit (0 or 1)
  • Set a bit to 1
  • Set a bit to 0

We first define an unsigned short type variable wInfo to store these flags. Then, we use bit operations to check and set the corresponding flags.

C++ example code

#include <iostream>
#include <bitset>

// 定义标志位常量
const unsigned short BIT_0_FAIL = 1 << 0;    // bit0 是否失败
const unsigned short BIT_1_COMPRESSED = 1 << 1; // bit1 是否压缩
const unsigned short BIT_2_INCREMENT = 1 << 2;  // bit2 是否增量
const unsigned short BIT_3_HAS_MORE = 1 << 3;   // bit3 是否有后续包
const unsigned short BIT_5_CANCEL = 1 << 5;     // bit5 正常请求(0)或注销(1)

// 检查某一位是否为1
bool isBitSet(unsigned short wInfo, unsigned short bitMask) {
    return (wInfo & bitMask) != 0;
}

// 设置某一位为1
void setBit(unsigned short& wInfo, unsigned short bitMask) {
    wInfo |= bitMask;
}

// 清除某一位(设置为0)
void clearBit(unsigned short& wInfo, unsigned short bitMask) {
    wInfo &= ~bitMask;
}

int main() {
    // 假设wInfo的初始值为0
    unsigned short wInfo = 0;

    // 设置bit0(失败标志)
    setBit(wInfo, BIT_0_FAIL);
    
    // 设置bit1(压缩标志)
    setBit(wInfo, BIT_1_COMPRESSED);
    
    // 打印wInfo的二进制值
    std::cout << "wInfo (in binary): " << std::bitset<16>(wInfo) << std::endl;

    // 检查各个标志位
    std::cout << "bit0 (是否失败): " << (isBitSet(wInfo, BIT_0_FAIL) ? "是" : "否") << std::endl;
    std::cout << "bit1 (是否压缩): " << (isBitSet(wInfo, BIT_1_COMPRESSED) ? "是" : "否") << std::endl;
    std::cout << "bit2 (是否增量): " << (isBitSet(wInfo, BIT_2_INCREMENT) ? "是" : "否") << std::endl;
    std::cout << "bit3 (是否有后续包): " << (isBitSet(wInfo, BIT_3_HAS_MORE) ? "是" : "否") << std::endl;
    std::cout << "bit5 (是否注销): " << (isBitSet(wInfo, BIT_5_CANCEL) ? "是" : "否") << std::endl;

    // 清除bit1(压缩标志)
    clearBit(wInfo, BIT_1_COMPRESSED);
    
    // 打印更新后的wInfo
    std::cout << "Updated wInfo (in binary): " << std::bitset<16>(wInfo) << std::endl;

    return 0;
}

Execute code, recommended by an old friend: https://wandbox.org/

wInfo (in binary): 0000000000000011
bit0 (是否失败): 是
bit1 (是否压缩): 是
bit2 (是否增量): 否
bit3 (是否有后续包): 否
bit5 (是否注销): 否
Updated wInfo (in binary): 0000000000000001

Code explanation

  1. Flag bits are defined using bit shift operations (1 << n). For example, 1 << 0 corresponds to bit0, 1 << 1 corresponds to bit1, and so on. This assigns a unique binary position to each flag bit.

  2. The isBitSet function checks if a specific flag is set to 1 by performing a bitwise AND operation wInfo & bitMask. If the bit is 1, the function returns true; otherwise, it returns false.

  3. The setBit function sets a specific flag to 1 using a bitwise OR operation wInfo |= bitMask

  4. The clearBit function sets a specific flag to 0 using a bitwise AND operation: wInfo &= ~bitMask

Summary

Through bit manipulation, we can efficiently handle multiple status flag bits. This technique is particularly useful in practical development. For example, it is often used in scenarios such as embedded development, network protocols, and system state management, where bit flags are used to represent multiple binary states, saving space and improving efficiency.

I hope this blog helps you understand how to use bitwise operations in C++ to achieve bit extraction and setting. Mastering these skills is very helpful for writing efficient and maintainable code!

Licensed under CC BY-NC-SA 4.0
Last updated on May 25, 2025 02:57
A financial IT programmer's tinkering and daily life musings
Built with Hugo
Theme Stack designed by Jimmy