22. 位运算,位字段
假设A代表一个二进制位,则有如下恒等式:
A & 0 = 0
A & 1 = A
A | 0 = A
A | 1 = 1
A ^ 0 = A
A ^ 1 = ~A
A ^ A = 0
A & ~A = 0
A | ~A = 1
如果
A ^ B = C
则
A ^ C = B
B ^ C = A
右移一个有符号数时,高位填符号位。
右移一个无符号数时,高位填0。
只用位运算求绝对值:
int myabs(int n) {
int sign = n >> 31;//负数得到0xffffffff,正数得到0x00000000
int res = (n ^ sign) - sign;//位运算优先级较低,记得加括号
return res;
}
位字段:
struct Access {
//WRES
unsigned Share : 1; //第0位
unsigned Execute : 1; //第1位
unsigned Read : 1; //第2位
unsigned Write : 1; //第3位
};
struct Access {
//WRES
//WW WWWW RRRR REEE ESSS
unsigned Share : 3; //第0~2位
unsigned Execute : 4; //第3~6位
unsigned Read : 5; //第7~11位
unsigned Write : 6; //第12~17位
};
Access acc = { 0 };
acc .Share = 0b111011; //只最后3位011赋值
acc .Execute = 0b111011011;//只最后4位1011赋值
acc .Read = 0b11110101011; //只最后5位01011赋值
acc .Write = 0b1110101011011;//只最后6位011011赋值
struct Access {
//WRES
//WWWW WWRR RRR? ?EEE ESSS
unsigned Share : 3; //第0~2位
unsigned Execute : 4; //第3~6位
unsigned : 2; //第7~8位,无名位字段,作者保留
unsigned Read : 5; //第9~13位
unsigned Write : 6; //第14~19位
};
struct Access {
//WRES
//WW WWWW RRRR REEE ESSS
unsigned Share : 3; //第0~2位
unsigned Execute : 4; //第3~6位
unsigned Read : 5; //第7~11位
unsigned Write : 6; //第12~17位
};
Access acc = { 0 };
acc .Share = 0b111011; //只最后3位011赋值
acc .Execute = 0b111011011;//只最后4位1011赋值
acc .Read = 0b11110101011; //只最后5位01011赋值
acc .Write = 0b1110101011011;//只最后6位011011赋值
struct Access {
//WRES
//WWWW WWRR RRR? ?EEE ESSS
unsigned Share : 3; //第0~2位
unsigned Execute : 4; //第3~6位
unsigned : 2; //第7~8位,无名位字段,作者保留
unsigned Read : 5; //第9~13位
unsigned Write : 6; //第14~19位
};

浙公网安备 33010602011771号