You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用位移位操作且不使用异或运算符实现二进制数的奇偶校验(精简代码方案)

Streamlined Bitwise Shift-Based Parity Check Implementation

Got it, let's break this down. Your original code calculates parity by iterating through a binary string's characters (starting from the second one) and flipping the parity flag whenever it hits a '1'. We can rewrite this using only bitwise shifts (no XOR allowed) while keeping the code tight and readable.

Option 1: Direct Character Processing with Bitwise Shifts

This approach retains string traversal but replaces the clunky switch-case with shift operations to flip the parity flag efficiently:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if (argc == 2) {
        int parity = 0;
        // Match original logic: start from the second character (index 1)
        for (int i = 1; i < strlen(argv[1]); i++) {
            int bit = (argv[1][i] == '1'); // Convert char to 0/1 bit value
            parity = (parity << 1) | bit;  // Shift left, OR with current bit to update state
            parity &= 1;                   // Keep only the least significant bit to flip parity
        }
        printf("The parity is: %d\n", parity);
    }
    return 0;
}

Option 2: Convert String to Integer First (For Shorter Binary Strings)

If your input binary string is short enough to fit into an unsigned int (typically 32 bits), converting it to an integer lets us leverage bitwise operations directly, skipping string traversal:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc == 2) {
        // Convert binary string to unsigned integer
        unsigned int num = strtoul(argv[1], NULL, 2);
        int parity = 0;
        
        num >>= 1; // Skip the first bit to match original code's starting point
        while (num) {
            parity = (parity << 1) | (num & 1); // Grab current bit, update parity state
            parity &= 1;
            num >>= 1; // Shift right to check the next bit
        }
        printf("The parity is: %d\n", parity);
    }
    return 0;
}

Key Tricks for Conciseness

  • Shift + AND for Parity Flip: Instead of if-else blocks or XOR, (parity << 1) | bit followed by & 1 effectively flips the parity when the bit is 1, and keeps it unchanged when the bit is 0—exactly what we need.
  • Simplified Bit Extraction: Replacing the switch-case with a boolean check (argv[1][i] == '1') cuts down on redundant code.
  • Integer Conversion: For shorter inputs, this method reduces overhead by working directly with binary values instead of string characters.

Note: Option 2 will overflow if your binary string exceeds the size of unsigned int (usually 32 bits). Stick with Option 1 for longer inputs.

内容的提问来源于stack exchange,提问作者Genodan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:27:28