简体   繁体   中英

How to compare unaligned single bits in two ints?

To compare the m -th bit in foo with the n -th bit in bar , I end up doing something like

if ( ( ( foo >> m ) & 1 ) == ( ( bar >> n ) & 1 ) ) {...}

or even

if ( ! ( ( ( foo >> m ) ^ ( bar >> n ) ) & 1 ) ) {...}

but this looks very suboptimal to me. I wonder if there a more straightforward way to do it.

for me a more readable way is

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

but it is not "better".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM