encode6bitbuf_final.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. """Encode6BitBuf 双向实现(最终验证版)
  3. 来源: 游戏二进制 0x10004b4e4/0x10004b594 逐指令翻译
  4. 验证: pcap心跳帧 round-trip 100% 匹配
  5. 表: Encode6BitBuf_替换表.bin (前256B=ENC, 后256B=DEC)
  6. """
  7. import os
  8. import struct
  9. _HERE = os.path.dirname(os.path.abspath(__file__))
  10. _tables = open(os.path.join(_HERE, "Encode6BitBuf_替换表.bin"), "rb").read()
  11. ENC_TABLE = _tables[:256]
  12. INV_TABLE = [0] * 256
  13. for _i, _v in enumerate(ENC_TABLE):
  14. INV_TABLE[_v] = _i
  15. def encode6(src: bytes) -> bytes:
  16. dst = bytearray()
  17. w14 = 0
  18. w12 = 0
  19. for byte in src:
  20. w16 = (ENC_TABLE[byte] ^ 9) & 0xFFFF
  21. new_w12 = w12 + 2
  22. w17 = w16 >> new_w12
  23. w14 |= w17
  24. out6 = w14 & 0x3F
  25. w14 = ((w16 << ((6 - w12) & 0xFF)) & 0xFFFFFFFF) >> 2 & 0x3F
  26. dst.append((out6 + 0x3C) & 0xFF)
  27. if w12 >= 4:
  28. w12 = 0
  29. dst.append((w14 + 0x3C) & 0xFF)
  30. w14 = 0
  31. else:
  32. w12 = new_w12
  33. if w12 > 0:
  34. dst.append((w14 + 0x3C) & 0xFF)
  35. return bytes(dst)
  36. def decode6(data: bytes) -> bytes:
  37. bits = 0
  38. nbits = 0
  39. raw = bytearray()
  40. for ch in data:
  41. v6 = ch - 0x3C
  42. if not (0 <= v6 <= 63):
  43. break
  44. bits = (bits << 6) | v6
  45. nbits += 6
  46. while nbits >= 8:
  47. nbits -= 8
  48. raw.append((bits >> nbits) & 0xFF)
  49. return bytes(INV_TABLE[b ^ 9] for b in raw)
  50. def build_frame(msg_id: int, recog: int, p1: int, p2: int, p3: int, extra: bytes = b"\x00"*12) -> bytes:
  51. """构造发送帧: 48字符头(Encode6(36B)) + body"""
  52. head36 = struct.pack("<8i", 0, msg_id, recog, p1, p2, p3, 0, 0) + extra[:4]
  53. return encode6(head36) # body由调用者拼接
  54. if __name__ == "__main__":
  55. # self-test: 心跳帧
  56. plain = struct.pack("<8i", 0, 60000, 1789709744, 0, 0, 149, 0, 0) + bytes.fromhex("70000000")
  57. enc = encode6(plain)
  58. expected = bytes.fromhex("5d5452415d4c67445d545078495e55525d5452415d5452415d54507a5d5452415d5452415d5452415d54527b5d545241")
  59. assert enc == expected, "round-trip FAIL"
  60. print("✓ 心跳帧编码验证通过")
  61. dec = decode6(expected)
  62. assert dec == plain, "decode FAIL"
  63. print("✓ 解码验证通过")