# -*- coding: utf-8 -*- """Encode6BitBuf 双向实现(最终验证版) 来源: 游戏二进制 0x10004b4e4/0x10004b594 逐指令翻译 验证: pcap心跳帧 round-trip 100% 匹配 表: Encode6BitBuf_替换表.bin (前256B=ENC, 后256B=DEC) """ import os import struct _HERE = os.path.dirname(os.path.abspath(__file__)) _tables = open(os.path.join(_HERE, "Encode6BitBuf_替换表.bin"), "rb").read() ENC_TABLE = _tables[:256] INV_TABLE = [0] * 256 for _i, _v in enumerate(ENC_TABLE): INV_TABLE[_v] = _i def encode6(src: bytes) -> bytes: dst = bytearray() w14 = 0 w12 = 0 for byte in src: w16 = (ENC_TABLE[byte] ^ 9) & 0xFFFF new_w12 = w12 + 2 w17 = w16 >> new_w12 w14 |= w17 out6 = w14 & 0x3F w14 = ((w16 << ((6 - w12) & 0xFF)) & 0xFFFFFFFF) >> 2 & 0x3F dst.append((out6 + 0x3C) & 0xFF) if w12 >= 4: w12 = 0 dst.append((w14 + 0x3C) & 0xFF) w14 = 0 else: w12 = new_w12 if w12 > 0: dst.append((w14 + 0x3C) & 0xFF) return bytes(dst) def decode6(data: bytes) -> bytes: bits = 0 nbits = 0 raw = bytearray() for ch in data: v6 = ch - 0x3C if not (0 <= v6 <= 63): break bits = (bits << 6) | v6 nbits += 6 while nbits >= 8: nbits -= 8 raw.append((bits >> nbits) & 0xFF) return bytes(INV_TABLE[b ^ 9] for b in raw) def build_frame(msg_id: int, recog: int, p1: int, p2: int, p3: int, extra: bytes = b"\x00"*12) -> bytes: """构造发送帧: 48字符头(Encode6(36B)) + body""" head36 = struct.pack("<8i", 0, msg_id, recog, p1, p2, p3, 0, 0) + extra[:4] return encode6(head36) # body由调用者拼接 if __name__ == "__main__": # self-test: 心跳帧 plain = struct.pack("<8i", 0, 60000, 1789709744, 0, 0, 149, 0, 0) + bytes.fromhex("70000000") enc = encode6(plain) expected = bytes.fromhex("5d5452415d4c67445d545078495e55525d5452415d5452415d54507a5d5452415d5452415d5452415d54527b5d545241") assert enc == expected, "round-trip FAIL" print("✓ 心跳帧编码验证通过") dec = decode6(expected) assert dec == plain, "decode FAIL" print("✓ 解码验证通过")