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

发布于 2024-12-05 13:35:04 字数 747 浏览 4 评论 0原文

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

00001111

数字 13 表示为:

00001101

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

编辑:我应该澄清一下,我知道 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++;
      }  
 }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╭ゆ眷念 2024-12-12 13:35:04

使用按位运算:

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

^ 或 XOR 的作用是:

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

一种思考方式是:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文