Files

34 lines
1008 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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