Let’s say you have a variable x.
- int x = 0b10100110;
Then in order to set the nth bit of x (counting from righthand side) to 1. You can write as follows:
- int y = x | (1 << n);
If you want to set the nth bit of x to 0, you can do it like this:
- int y = x & ~(1 << n);
If you want to flip the nth bit of x, you can write like this:
- int y = x ^ (1 << n)
You can easily turn these into macros.
- #define SETBIT(num,bitpos) (num|(1<<bitpos))
- #define CLRBIT(num,bitpos) (num&(~(1<<bitpos)))
No comments:
Post a Comment