# 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
我想这是序列化+编码的一种形式。你知道吗
基本上,您需要生成一个包含各种秘密值的字节数组(这就是大多数binary protocols的写入方式),然后将每个字节编码成一个(或多个)相应的字符,以便输出“string”是可读的。下面是如何在Python中将数据序列化为字节数组的示例:
玩家信息
设置序列化信息
执行序列化
检索单个值
相关问题 更多 >
编程相关推荐