C语言 如何比较C中的两个位值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7479309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:40:26  来源:igfitidea点击:

How to compare two bit values in C?

cbit-manipulationxor

提问by thomascirca

I've been dabbling around a bit with C and I find that being able to directly manipulate bits is fascinating and powerful (and dangerous I suppose). I was curious as to what the best way would be to compare different bits in C would be. For instance, the number 15 is represented in binary as:

我一直在尝试使用 C 语言,我发现能够直接操作位是令人着迷和强大的(我想也是危险的)。我很好奇在 C 中比较不同位的最佳方法是什么。例如,数字 15 以二进制表示为:

00001111

And the number 13 is represented as:

数字 13 表示为:

00001101

How would you compare what bits are different without counting them? It would be easy to use shifts to determine that 15 contains 4 1s and 13 contains 3 1s, but how would you output the difference between the two (ex that the 2^1 spot is different between the two)? I just can't think of an easy way to do this. Any pointers would be much appreciated!

如果不计算它们,您将如何比较哪些位不同?使用移位来确定 15 包含 4 个 1 并且 13 包含 3 个 1 很容易,但是您将如何输出两者之间的差异(例如,两者之间的 2^1 点不同)?我只是想不出一个简单的方法来做到这一点。任何指针将不胜感激!

EDIT: I should have clarified that I know XOR is the right way to go about this problem, but I had an issue with implementation. I guess my issue was comparing one bit at a time (and not generating the difference per say). The solution I came up with is:

编辑:我应该澄清一下,我知道 XOR 是解决这个问题的正确方法,但我在实现方面遇到了问题。我想我的问题是一次比较一点(而不是产生差异)。我想出的解决方案是:

 void compare(int vector1, int vector2) {         
     int count = 0; 
     unsigned int xor = vector1 ^ vector2;

     while (count < bit_length) {
          if (xor % 2 == 1) { //would indicicate a difference
               printf("%d ", count);
          }
          xor >>= 1; 
          count++;
      }  
 }

回答by Mateen Ulhaq

Use bitwise operations:

使用按位运算:

c         = a         ^ b        ;
00000010b = 00001111b ^ 00001101b;


What ^, or XOR, does is:

什么^,或XOR,做的是:

0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0

One way of thinking about it would be:

一种思考方式是:

If the two operands (aand b) are different, the result is 1.
If they are equal, the result is 0.

如果两个操作数 (ab) 不同,则结果为1
如果它们相等,则结果为0