Bitwise Operators in C: Bit Masking, Flag Toggling & Shift Rules

Bitwise operators in c are used for low-level hardware control, network protocol framing, and cryptography to manipulate individual bits in an unsigned integer. There are six bitwise operators in c: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (one's complement inversion), << (left shift) and >> (right shift). In c, always use unsigned integer types (e.g., uint32_t or unsigned int) when using bitwise operators, since C17 specifies that shifting into the sign bit of a signed integer type, or shifting by a negative count or by a width greater than or equal to the integer type is undefined behavior.

Bitwise Operators in C: AND, OR, XOR, NOT & Safe Unsigned Shifts — Technical Overview

Bitwise operators in c are used for low-level hardware control, network protocol framing, and cryptography to manipulate individual bits in an unsigned integer. There are six bitwise operators in c: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (one's complement inversion), << (left shift) and >> (right shift). In c, always use unsigned integer types (e.g., uint32_t or unsigned int) when using bitwise operators, since C17 specifies that shifting into the sign bit of a signed integer type, or shifting by a negative count or by a width greater than or equal to the integer type is undefined behavior.

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t reg = 0x00U;
    reg |= (1U << 3);  /* Set bit 3 */
    reg ^= (1U << 1);  /* Toggle bit 1 */
    printf("Register mask = 0x%02X (bit 3 set: %u)\n", reg, (reg >> 3) & 1U);
    return 0;
}

Runnable C example

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t reg = 0x00U;
    reg |= (1U << 3);  /* Set bit 3 */
    reg ^= (1U << 1);  /* Toggle bit 1 */
    printf("Register mask = 0x%02X (bit 3 set: %u)\n", reg, (reg >> 3) & 1U);
    return 0;
}

Open example in compiler

Expected Output

Register mask = 0x0A (bit 3 set: 1)