开发者

How to compare two bit values in C?

开发者 https://www.devze.com 2023-04-06 04:58 出处:网络
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

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开发者_如何学JAVA 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++;
      }  
 }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消