python:UnicodeDecodeError:'utf8'编解码器无法解码位置0的字节0xc0:无效的起始字节
我正在尝试编写一个脚本,该脚本通过创建随机utf-8编码的字符串,然后将其解码为unicode来生成随机unicode。对于单个字节,它工作正常,但是对于两个字节,它将失败。
例如,如果我在python shell中运行以下命令:
>>> a = str()
>>> a += chr(0xc0) + chr(0xaf)
>>> print a.decode('utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc0 in position 0: invalid start byte
根据utf-8方案https://en.wikipedia.org/wiki/UTF-8#Description,字节序列0xc0
0xaf
应以0xc0
开头110
和0xaf
开头都有效10
。
这是我的python脚本:
def unicode(self):
'''returns a random (astral) utf encoded byte string'''
num_bytes = random.randint(1,4)
if num_bytes == 1:
return self.gen_utf8(num_bytes, 0x00, 0x7F)
elif num_bytes == 2:
return self.gen_utf8(num_bytes, 0xC0, 0xDF)
elif num_bytes == 3:
return self.gen_utf8(num_bytes, 0xE0, 0xEF)
elif num_bytes == 4:
return self.gen_utf8(num_bytes, 0xF0, 0xF7)
def gen_utf8(self, num_bytes, start_val, end_val):
byte_str = list()
byte_str.append(random.randrange(start_val, end_val)) # start byte
for i in range(0,num_bytes-1):
byte_str.append(random.randrange(0x80,0xBF)) # trailing bytes
a = str()
sum = int()
for b in byte_str:
a += chr(b)
ret = a.decode('utf-8')
return ret
if __name__ == "__main__":
g = GenFuzz()
print g.gen_utf8(2,0xC0,0xDF)