AJ.
AJ.

Reputation: 2569

C bitmap giving one value higher than expected

I am using following code to create a bitmap in C and enable a bit. But problem is when I am reading it I am getting one higher bit enabled than expected.

#define BITS_PER_WORD (sizeof(uint32_t) * CHAR_BIT)
#define WORD_OFFSET(b) ((b) / BITS_PER_WORD)
#define BIT_OFFSET(b)  ((b) % BITS_PER_WORD)

main ()
{
// declarations
int val = 2;
init_bits(&bmp);
set_bit(&bmp,val);

for (id = 0; id < sizeof(bmp); id++)
        {
            if (bmp & (1 << id))
            {
                trace(debug, "bit:%x", bmp,);
            }
        }
}

init_bits(uint32_t *words) {
     (void)memset((void*)words, 0, sizeof(uint32_t));
}

set_bit(uint32_t *words, int n) {
      words[WORD_OFFSET(n)] |= (1 << BIT_OFFSET(n));
}

so for example if I execute set_bit(&bmp,2) then I am getting 4(instead of 2) in hex and 10 (instead of 8) for set_bit(&bmp,4) and so on.

Any help is greatly appreciated!

Upvotes: 0

Views: 53

Answers (1)

rodrigo
rodrigo

Reputation: 98358

I think your expectations are wrong. The usual way to work is:

  • set_bit(0) -> 1
  • set_bit(1) -> 2
  • set_bit(2) -> 4
  • set_bit(3) -> 8
  • set_bit(4) -> 16 (0x10)
  • set_bit(5) -> 32 (0x20)
  • set_bit(6) -> 64 (0x40)
  • set_bit(7) -> 128 (0x80)

Note that this is exactly the value of the mathematical base-2-exponent function.

If you want any other convention, you'll have to add or substract accordingly.

Upvotes: 5

Related Questions