我希望这是一种序列化+编码的形式。
您基本上需要生成一个包含各种秘密值的字节数组(这是大多数二进制协议的编写方式),然后将每个字节编码为相应的字符(或更多),以便输出“字符串”可读。下面是如何在 Python 中将数据序列化为字节数组的示例:
玩家信息
player_name = "Robert"
player_stats = {
"health": 200,
"mana": 150,
"has_sword": True,
"has_arrows": False,
"has_shovel": True,
"dungeon1_complete": True
}
设置序列化信息
# If these can be greater than 255, they must be stored across multiple bytes - extra work
byte_attribs = ["health", "mana"]
bit_attribs = ["has_sword", "has_arrows", "has_shovel", "dungeon1_complete"]
player_name_max_length = 7
byte_attrib_offset = player_name_max_length
bit_attrib_offset = byte_attrib_offset + len(byte_attribs)
secret_storage = bytearray(bit_attrib_offset + len(bit_attribs))
assert(len(player_name) <= player_name_max_length)
执行序列化
# Serialize Player Name
secret_storage[:player_name_max_length] = player_name.rjust(player_name_max_length)
# Serialize attributes:
for idx, attrib in enumerate(byte_attribs):
secret_storage[byte_attrib_offset + idx] = player_stats[attrib]
for idx, attrib in enumerate(bit_attribs):
byte_offset = idx // 8 # attribs 0-7 go in byte 0, etc.
bit_offset = idx % 8
# Bit manipulation examples: http://wiki.python.org/moin/BitManipulation
current_byte = bit_attrib_offset + byte_offset
if player_stats[attrib]:
mask = 1 << bit_offset
secret_storage[current_byte] = secret_storage[current_byte] | mask
else:
mask = ~(1 << bit_offset)
secret_storage[current_byte] = secret_storage[current_byte] & mask
检索单个值
print "Storage array encoded as ascii:", secret_storage
# Access name:
print "Name:", secret_storage[:player_name_max_length].lstrip()
# >>> Name: Robert
# Access byte values:
attrib_idx = byte_attribs.index("mana")
print "Mana level:", secret_storage[byte_attrib_offset + attrib_idx]
# >>> Mana level: 150
# Access bit flags:
attrib_idx = bit_attribs.index("dungeon1_complete")
print "Completed Dungeon 1:", bool(secret_storage[bit_attrib_offset + (attrib_idx // 8)] & (1 << attrib_idx % 8))
# >>> Completed Dungeon 1: True