Files
protocol_convert_software_BD3/core/bit_packer.py

31 lines
856 B
Python
Raw Normal View History

"""
2026/4/5
TMY
比特位打包器
"""
class BitPacker:
def __init__(self, total_bytes):
self.buf = bytearray(total_bytes)
def set_bits(self, start_byte, start_bit, bit_len, value):
"""
start_byte: 起始字节
start_bit: 起始比特位0~7
bit_len: 比特长度
value: 无符号整数值
"""
value = int(value) & ((1 << bit_len) - 1)
bit_pos = start_byte * 8 + start_bit
for i in range(bit_len):
bit = (value >> (bit_len - 1 - i)) & 1
byte_idx = bit_pos // 8
bit_idx = 7 - (bit_pos % 8)
if bit:
self.buf[byte_idx] |= (1 << bit_idx)
else:
self.buf[byte_idx] &= ~(1 << bit_idx)
bit_pos += 1
def get_bytes(self):
return bytes(self.buf)