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

C语言中位运算符的完整用法和实际应用场景是什么?

2月18日 17:17

C语言中位运算符的完整用法和实际应用场景是什么?

位运算符列表:

  1. 按位与 &

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

    c
    unsigned int result = a | b; // 0b11101110 (238)
  3. 按位异或 ^

    c
    unsigned int result = a ^ b; // 0b01100110 (102)
  4. 按位取反 ~

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

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

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

实际应用场景:

  1. 位掩码操作

    c
    #define FLAG_A 0x01 // 00000001 #define FLAG_B 0x02 // 00000010 #define FLAG_C 0x04 // 00000100 unsigned int flags = 0; // 设置标志位 flags |= FLAG_A; flags |= FLAG_B; // 清除标志位 flags &= ~FLAG_A; // 检查标志位 if (flags & FLAG_B) { printf("FLAG_B is set\n"); } // 切换标志位 flags ^= FLAG_C;
  2. 位域操作

    c
    struct BitField { unsigned int flag1 : 1; unsigned int flag2 : 1; unsigned int value : 6; };
  3. 快速计算

    c
    // 乘以2的幂 int x = 5; int result = x << 3; // x * 8 = 40 // 除以2的幂 int result = x >> 2; // x / 4 = 1 // 判断奇偶 if (x & 1) { printf("Odd\n"); } else { printf("Even\n"); }
  4. 数据压缩

    c
    // 将两个8位值打包成16位 uint8_t low = 0xAB; uint8_t high = 0xCD; uint16_t packed = (high << 8) | low; // 0xCDAB // 解包 uint8_t extracted_low = packed & 0xFF; uint8_t extracted_high = (packed >> 8) & 0xFF;
  5. 哈希计算

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

注意事项:

  • 有符号数的右移行为依赖于实现
  • 位运算优先级低于比较运算符
  • 避免对负数进行位运算
  • 移位次数不能超过或等于类型的位数
标签:C语言