简体   繁体   English

如何在 python 中创建一个在 for 循环期间更改值的字节变量?

[英]How to create a byte variable that change value during for loop in python?

I want to print differences between utf-8 and utf-16 for all characters in range \x00\x00\x00\x00 to \xff\xff\xff\xff and I was thinking to do in this way:我想为\x00\x00\x00\x00\xff\xff\xff\xff范围内的所有字符打印 utf-8 和 utf-16 之间的差异,我想这样做:

for i in range (0x10):
  h = hex(i)[2:3]
  byte = b"\x00\x00\x00\x0{i}"

print(byte.decode('utf-16', 'ignore'))
print(byte.decode('utf-8', 'ignore'))

where the i into the byte variable change during the loop and using nested loop to cover all bytes in byte variable.其中 i 在循环期间更改为字节变量,并使用嵌套循环覆盖字节变量中的所有字节。
Is possible to do something like that?有可能做这样的事情吗?
Exists another way to print all byte from \x00\x00\x00\x00 to \xff\xff\xff\xff in python?是否存在另一种打印 python 中从\x00\x00\x00\x00\xff\xff\xff\xff的所有字节的方法?

The struct module is a nice tool to build byte strings. struct模块是构建字节字符串的好工具。 Here you could generate yours that way:在这里,您可以通过这种方式生成您的:

for i in range(0x10):
    b = struct.pack('>I', i)   # convert an int to a big endian 4 bytes string
    print(b)

It gives as expected:它按预期给出:

b'\x00\x00\x00\x00'
b'\x00\x00\x00\x01'
b'\x00\x00\x00\x02'
b'\x00\x00\x00\x03'
b'\x00\x00\x00\x04'
b'\x00\x00\x00\x05'
b'\x00\x00\x00\x06'
b'\x00\x00\x00\x07'
b'\x00\x00\x00\x08'
b'\x00\x00\x00\t'
b'\x00\x00\x00\n'
b'\x00\x00\x00\x0b'
b'\x00\x00\x00\x0c'
b'\x00\x00\x00\r'
b'\x00\x00\x00\x0e'
b'\x00\x00\x00\x0f'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM