Normally bits are numbered from right to left. If you used that standard convention and a start-stop value (like a range), your functions would be simpler to implement with bitwise operators:
def get_bits(n, start, end):
return (n&((1<<end)-1))>>start
def set_bits(n, start, end, value):
mask = (1<<end) - (1<<start)
return (n&~mask) | (value<<start)&mask
output:
n = 341 # 101010101
# 876543210 bit numbers
# 101010101 = 341
f"{get_bits(n,3,7):b}" # ..1010... = 10
# 876543210
# 101010101 = 341
f"{set_bits(n,3,7,12):b}" # 101100101 = 357
# ..^^^^...
# ..1100... = 12
# 876543210
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…