Reputation: 2569
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
Reputation: 98358
I think your expectations are wrong. The usual way to work is:
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