#include<stdio.h> unsignedreplace_byte(unsigned x, int i, unsignedchar b) { x = x & (~(0XFF << (i << 3)));//相应字节置零 x = x | (b << (i << 3)); //相应字节改为char b return x; } intmain() { unsigned ret = replace_byte(0X12345678, 1, 0XAB); printf("0X%X\n", ret); return0; }
0X1234AB78
利用按位运算$x \& 1 = x , b | 0 = b$。
Csapp 2.65
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<stdio.h> intodd_ones(unsigned x) { x ^= x >> 16; x ^= x >> 8; x ^= x >> 4; x ^= x >> 2; x ^= x >> 1; return x & 1; } intmain() { int x = odd_ones(0XB); printf("%d\n", x); return0; }