乐闻世界logo
搜索文章和话题

What is the complete usage and practical application scenarios of bitwise operators in C language?

2月18日 17:17

What is the complete usage and practical application scenarios of bitwise operators in C language?

Bitwise Operators List:

  1. Bitwise AND &

    c
    unsigned int a = 0b10101010; // 170 unsigned int b = 0b11001100; // 204 unsigned int result = a & b; // 0b10001000 (136)
  2. Bitwise OR |

    c
    unsigned int result = a | b; // 0b11101110 (238)
  3. Bitwise XOR ^

    c
    unsigned int result = a ^ b; // 0b01100110 (102)
  4. Bitwise NOT ~

    c
    unsigned int result = ~a; // 0b01010101 (85)
  5. Left Shift <<

    c
    unsigned int result = a << 2; // 0b1010101000 (680)
  6. Right Shift >>

    c
    unsigned int result = a >> 2; // 0b00101010 (42)

Practical Application Scenarios:

  1. Bit Mask Operations

    c
    #define FLAG_A 0x01 // 00000001 #define FLAG_B 0x02 // 00000010 #define FLAG_C 0x04 // 00000100 unsigned int flags = 0; // Set flag flags |= FLAG_A; flags |= FLAG_B; // Clear flag flags &= ~FLAG_A; // Check flag if (flags & FLAG_B) { printf("FLAG_B is set\n"); } // Toggle flag flags ^= FLAG_C;
  2. Bit Field Operations

    c
    struct BitField { unsigned int flag1 : 1; unsigned int flag2 : 1; unsigned int value : 6; };
  3. Fast Calculations

    c
    // Multiply by power of 2 int x = 5; int result = x << 3; // x * 8 = 40 // Divide by power of 2 int result = x >> 2; // x / 4 = 1 // Check odd/even if (x & 1) { printf("Odd\n"); } else { printf("Even\n"); }
  4. Data Compression

    c
    // Pack two 8-bit values into 16-bit uint8_t low = 0xAB; uint8_t high = 0xCD; uint16_t packed = (high << 8) | low; // 0xCDAB // Unpack uint8_t extracted_low = packed & 0xFF; uint8_t extracted_high = (packed >> 8) & 0xFF;
  5. Hash Calculation

    c
    unsigned int hash = 0; for (int i = 0; i < len; i++) { hash = (hash << 5) ^ str[i]; }

Important Considerations:

  • Right shift behavior for signed numbers is implementation-dependent
  • Bitwise operators have lower precedence than comparison operators
  • Avoid bitwise operations on negative numbers
  • Shift count must be less than the number of bits in the type
标签:C语言