简体   繁体   English

如何比较C中的两位值?

[英]How to compare two bit values in C?

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). 我一直在研究C语言,我发现能够直接操作位令人着迷且功能强大(我想这很危险)。 I was curious as to what the best way would be to compare different bits in C would be. 我很好奇,最好的方法是比较C中的不同位。 For instance, the number 15 is represented in binary as: 例如,数字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)? 容易使用移位来确定15包含4 1,而13包含3 1,但是您将如何输出两者之间的差异(例如,两者之间的2 ^ 1点不同)? I just can't think of an easy way to do this. 我只是想不出一种简单的方法来做到这一点。 Any pointers would be much appreciated! 任何指针将不胜感激!

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. 编辑:我应该澄清一下,我知道XOR是解决此问题的正确方法,但是我在实现上遇到了问题。 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: 我想出的解决方案是:

 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++;
      }  
 }

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 ( a and b ) are different, the result is 1 . 如果两个操作数( ab )不同,则结果为1
If they are equal, the result is 0 . 如果它们相等,则结果为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM