Eques
Eques

Reputation: 327

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.

Upvotes: 0

Views: 84

Answers (1)

linluk
linluk

Reputation: 1670

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".

Upvotes: 1

Related Questions