特别的二进制运算

## 快速求2的n次幂
print(10>>1)
print(13>>1)
print(13<<1)
print(-3<<1)
print(1<<10)  # 快速求2的n次幂
print(1<<4)  # 快速求2的n次幂
# print(-0.6<<1) # 这个无法运算
'''
检验奇偶性
'''

x = 11 # 8+2+1 ==>1011
if (x & 1) == 0:
    print( 'x是偶数')
else:
    print( 'x是奇数')
'''
交换两个元素'''
a, b = 1, 2
a ^= b
b ^= a
a ^= b
print(a, b)

'''
快速求余数,除数C刚好是2的n次幂才有效
'''
C = 1 << 10
X = 123456789
r1 = x % C
r2 = x & (C - 1)
print(r1, r2)
'''
找出只出现1次的数
a = 88
a ^ a = 0   任何数和他本身做位异或运算等于0
a ^ 0 = a   任何数和0做位异或运算等于本身
'''
## 找出列表中只出现一次的数
arr =[20,30,20,10,10]
ret = arr[0]

for i in range(1,len(arr)):
    ret ^= arr[i]
    print('这是i',i)
print(ret)
'''
利用位运算进行简单加密
'''
x = 1346852
key = 23333333333
encrypt = x ^ key
print(encrypt)
decrypt = encrypt ^ key
print(decrypt)
'''
获取某个数的二进制第k位
'''
#1001
a = 9
k = 3
print((a & (1 << k)) >> k)
k = 2
print((a & (1 << k)) >>k)

'''
将二进制的第k位设置为1
'''
a= 1 <<10
k = 3

a = (a | (1 << k))
print(a)
posted @ 2023-08-14 13:57  ty1539  阅读(15)  评论(0编辑  收藏  举报