How to compare two bit values in C?

妖精的绣舞 提交于 2019-12-11 00:14:29

问题


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:

00001111

And the number 13 is represented as:

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!

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:

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

回答1:


Use bitwise operations:

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

What ^, or XOR, does is:

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.
If they are equal, the result is 0.



来源:https://stackoverflow.com/questions/7479309/how-to-compare-two-bit-values-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!