使用技巧
- and
and 1:取二进制的最末位,可用于判断奇偶性 - or
or 1(/0):二进制最末位强行变成1(/0) - xor
0和1 xor 0都不变, xor 1则取反
逆运算:(a xor b) xor b = a,用于简单加密 - not
not 无符号整数:与该类型上界的差
not 有符号整数:not a ==> -a-1 - shl 左移
a shl b ==> a*2^b - shr 右移
a shl b ==> a/2^b
功能 | 示例 | 位运算 |
---|---|---|
去掉最后一位 | (101101->10110) | x shr 1 |
在最后加一个0 | (101101->1011010) | x shl 1 |
在最后加一个1 | (101101->1011011) | x shl 1+1 |
把最后一位变成1 | (101100->101101) | x or 1 |
把最后一位变成0 | (101101->101100) | x or 1-1 |
最后一位取反 | (101101->101100) | x xor 1 |
把右数第k位变成1 | (101001->101101,k=3) | x or (1 shl (k-1)) |
把右数第k位变成0 | (101101->101001,k=3) | x and not (1 shl (k-1)) |
右数第k位取反 | (101001->101101,k=3) | x xor (1 shl (k-1)) |
取末三位 | (1101101->101) | x and 7 |
取末k位 | (1101101->1101,k=5) | x and (1 shl k-1) |
取右数第k位 | (1101101->1,k=4) | x shr (k-1) and 1 |
把末k位变成1 | (101001->101111,k=4) | x or (1 shl k-1) |
末k位取反 | (101001->100110,k=4) | x xor (1 shl k-1) |
把右边连续的1变成0 | (100101111->100100000) | x and (x+1) |
把右起第一个0变成1 | (100101111->100111111) | x or (x+1) |
把右边连续的0变成1 | (11011000->11011111) | x or (x-1) |
取右边连续的1 | (100101111->1111) | (x xor (x+1)) shr 1 |
去掉右起第一个1的左边 | (100101000->1000) | x and (x xor (x-1)) |
一些数学知识:
#和@互为逆运算,下面代码swap两个值
x = x # y
y = x @ y
x = x @ y