如何比较C中的两个位值? [英] How to compare two bit values in C?

查看:88
本文介绍了如何比较C中的两个位值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在摸索C语言,发现能够直接操作位令人着迷且功能强大(我想这很危险).我很好奇,最好的方法是比较C中的不同位.例如,数字15用二进制表示为:

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

数字13表示为:

00001101

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

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!

我应该澄清一下,我知道XOR是解决此问题的正确方法,但是我在实现上遇到了问题.我想我的问题是一次只比较一点(而不是每句话产生差异).我想出的解决方案是:

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

推荐答案

使用按位运算:

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


^或XOR的作用是:


What ^, or XOR, does is:

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

一种思考的方式是:

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

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

这篇关于如何比较C中的两个位值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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