首次提交完整的python工程代码
This commit is contained in:
34
core/bit_tools.py
Normal file
34
core/bit_tools.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
2026/4/18
|
||||
Tan Mingyan
|
||||
新建 比特 / 字节 操作工具(通用、精准)
|
||||
"""
|
||||
def set_bits(data: bytearray, byte_offset: int, bit_offset: int, bit_length: int, value: int):
|
||||
"""
|
||||
对字节数组指定位置写入指定位数的值
|
||||
:param data: 原始字节数组(会被修改)
|
||||
:param byte_offset: 起始字节(从0开始,用户数据域起始为0)
|
||||
:param bit_offset: 起始比特(0~7)
|
||||
:param bit_length: 占多少比特
|
||||
:param value: 要写入的值
|
||||
"""
|
||||
if byte_offset >= len(data):
|
||||
return
|
||||
|
||||
# 生成掩码
|
||||
max_val = (1 << bit_length) - 1
|
||||
value = value & max_val
|
||||
|
||||
pos = byte_offset * 8 + bit_offset
|
||||
for i in range(bit_length):
|
||||
bit = (value >> (bit_length - 1 - i)) & 1
|
||||
byte_idx = pos // 8
|
||||
bit_idx = pos % 8
|
||||
|
||||
if byte_idx >= len(data):
|
||||
break
|
||||
|
||||
# 清位 + 置位
|
||||
data[byte_idx] &= ~(1 << (7 - bit_idx))
|
||||
data[byte_idx] |= (bit << (7 - bit_idx))
|
||||
pos += 1
|
||||
Reference in New Issue
Block a user