简体   繁体   中英

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:

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.
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?

The struct module is a nice tool to build byte strings. 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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