int x; // the value to be option
int b; // the value to set, 1 or 0
int n; // the position of x to be set.
x = b & 1 ? (1 << n | x) : ~(1 << n) & x;
// or
x ^= (-b ^ x) & 1 << n;
源代码:
#include <stdio.h>
#include <stdlib.h>
/*set the bit of n position to be b, n start from 0.*/
#define SET_BIT(x, n, b) \
do { \
x ^= (-b ^ x) & 1 << n; \
} while(0)
void main()
{ /* ((x & (((1<<sizeof(x)*8+1-n)-1)<<n)) */
int x = 0x8;
SET_BIT(x, 0, 1);
printf("%x", x);
}
测试结果: