To set the n-th bit:
num |= 1UL << n;
To clear the n-th bit:
num &= ~(1UL << n);
To toggle the n-th bit:
num ^= 1UL << n;
To check if n-th bit is set:
bit = (num >> n) & 1U;
To set the n-th bit to x
in two’s complement:
num ^= (-x ^ num) & (1UL << n);
To set the n-th bit to x
(regardless of representation):
num ^= (-(unsigned long)x ^ num) & (1UL << n);
Alternatively use a bitset
.