[英]How to compare unaligned single bits in two ints?
為了比較m
個位foo
與n
在個位bar
,我最后做這樣的事情
if ( ( ( foo >> m ) & 1 ) == ( ( bar >> n ) & 1 ) ) {...}
甚至
if ( ! ( ( ( foo >> m ) ^ ( bar >> n ) ) & 1 ) ) {...}
但這對我來說不是很理想。 我想知道是否有更簡單的方法來做到這一點。
對我來說,更易讀的方式是
#include <stdio.h>
int main() {
int foo, bar;
int foo_bit, bar_bit;
int foo_mask, bar_mask;
foo = 60; // 0b00111100
bar = 240; // 0b11110000
foo_bit = 3;
bar_bit = 5;
foo_mask = 1 << foo_bit;
bar_mask = 1 << bar_bit;
if((foo & foo_mask)>0 == (bar & bar_mask)>0) {
printf("bit %d in foo and bit %d in bar are equal\n",foo_bit,bar_bit);
} else {
printf("bit %d in foo and bit %d in bar are NOT equal\n",foo_bit,bar_bit);
}
return 0;
}
但這不是“更好”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.