unsigned int a; // value to merge in non-masked bits unsigned int b; // value to merge in masked bits unsigned int mask; //if mask=1,结果数据从b中选择,else 从a中选择 unsigned int r; //结果r= (a & ~mask) | (b & mask) r = a ^ ((a ^ b) & mask);
C测试代码:
1 #include<stdio.h> 2 #include<string.h> 3 4 int main() 5 { 6 unsigned int a; 7 unsigned int b; 8 unsigned int mask; 9 unsigned int r; 10 a=2; b=4; mask=0; 11 r = a ^ ((a ^ b) & mask); 12 printf("%d\n",r); 13 getchar(); 14 getchar(); 15 return 0; 16 } 17 18 /* 19 a:00000010 20 b:00000100 21 ^--------- 22 (a^b):00000110 23 mask:00000000 24 &--------- 25 00000000 26 a:00000010 27 ^--------- 28 00000010 29 30 ------------------------ 31 a:00000010 32 b:00000100 33 ^--------- 34 (a^b):00000110 35 mask:00000001 36 &--------- 37 00000000 38 a:00000010 39 ^--------- 40 00000010 41 42 */