C语言中如何比较两个位的值?
我一直在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用按位运算:
^
或 XOR 的作用是:一种思考方式是:
Use bitwise operations:
What
^
, or XOR, does is:One way of thinking about it would be: