Python之路——位运算
位运算:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
a = 125 # 125 = 0111 1101 b = 32 # 32 = 0010 0000 c = 0 #按位与运算 c = a & b; # 32 = 0010 0000 #两1为1,否则为0 print("按位与c:", c) #按位与c: 32 #按位或运算 c = a | b; # 125 = 0111 1101 #遇1为1,否则为0 print("按位或c:", c) #按位与c: 125 #按位异或运算 c = a ^ b; # 93 = 0101 1101 #相同为0,不同为1 print("按位异或运算c:", c) #按位异或运算c: 93 #按位取反运算 c = ~a; # -126 = 1000 0010 #取反,1换0 0换1 print("按位取反运算c:", c) #按位取反运算c: -126 #左移<<运算 c = a << 2; # 500 =0001 1111 0100 #向左异两位 print("左移<<运算c:", c) #左移<<运算c: 500 #右移>>运算 c = a >> 2; # 31 =0001 1111 #向右异两位 print("右移>>运算c:", c) #右移>>运算c: 31
*按位取反运算规则(按位取反再加1)