如何在C中对单个数字的所有位进行异或? [英] How to XOR all of the bits of a single number in C?

查看:27
本文介绍了如何在C中对单个数字的所有位进行异或?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以将单个数字的所有位异或在一起,即 C 中的一元异或?

Is there a simple way to XOR all of the bits of a single number together, i.e. a unary XOR in C?

具有以下效果的东西:

result = ^(0x45); // ( 0 ^ 1 ^ 0 ^ 0 ^ 0 ^ 1 ^ 0 ^ 1 = 1)
result = ^(0x33); // ( 0 ^ 0 ^ 1 ^ 1 ^ 0 ^ 0 ^ 1 ^ 1 = 0)

推荐答案

没有特殊的运算符.您需要按如下方式手动执行此操作:

There's no special operator for that. You would need to do that manually as follows:

unsigned int value = 0x45;
unsigned int result = 0;
while (value) {
    result ^= value & 1;
    value >>= 1;
}

您还可以创建一个包含所有 1 字节值的奇偶校验的查找表:

You can also create a lookup table containing the parity for all 1 byte values:

char parity[256] = { 0, 1, 1, 0, 1, 0, 0, 1,
                    ...
                     1, 0, 0, 1, 0, 1, 1, 0 };

这篇关于如何在C中对单个数字的所有位进行异或?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆