其他
整数与列表的转换
# 1. 把整数转换成每一位组成的列表 123 ->[1,2,3]
num = 1234
print(list(str(num)))
# [1,2,3] len 3 i 0~0
# [1,2,3,4] len 4 i 0~1
# [1,2,3,4,5] len 5 i 0~2
# len n i 0~n//2-1
def reverse_list(li):
n = len(li)
for i in range(n//2):
li[i], li[n-1-i] = li[n-1-i], li[i] # 0~n-1 1~n-2
return li
# print(reverse_list([1,2,4,5]))
def int2list(num):
li = []
while num > 0:
# 添加进去的数字是 反着的
li.append(num % 10)
num = num // 10
# 反转 列表
li.reverse()
return li
# [1,2,3,4,5] -> 12345
# 12345
def list2int(li):
num = 0
for val in li:
num = num * 10 + val
return num
print(list2int([1,2,3,4,5]))
反转数字
# 12345 -> 54321 123400->4321
def inverse_int(num):
res = 0
while num > 0:
res = res * 10 + num % 10
num = num // 10
return res
print(inverse_int(10002345))
数字转 二进制
def int2bin(num):
binary = []
while num > 0:
binary.append(num % 2)
num = num >> 1 # num // 2
binary.reverse()
return binary
print(int2bin(1234))
# & (按位与) | ~ ^ 异或(xor)
# and or not
# 位运算
print(3 ^ 6) # 5
# 0011
# 0110
# 0101
# 开关
x = False
def toggle(x):
return x ^ True
print(toggle(x))
# & 子网掩码
# 192.168.53.5/18
# &
# 255.255.255.0
# 11000000
# 192.168.0.0
# << >> 移位运算符
# 相当于平板除 效率高 二进制运算位移
print(17 >> 4) # 1
# 乘法运算
print(256 * 19)
# 19 = (16+2+1) 10011
print((256<<4)+(256<<1)+256)
# ^
# a ^ 0 = a a ^ a = 0
# 找出没有配对的 单独的 数字
li = [2,3,2,4,1,3,4,1,4]
x = 0
for val in li:
x = x ^ val
print(x)