Python 0x hexadecimal output without zero padding, Integer 16 hex, 16 hex string transfer

Python 0x hexadecimal output without zero padding, Integer 16 hex, 16 hex string transfer

  In development, we occasionally encounter the need to print out the data through the console to check the accuracy of data transmission. Such as debug server just to binary data (which contains many non-visible character, i.e. a value other than ASCii byte code or byte values ​​are not letters and numbers, some special symbols), such as the Internet of Things information MQTT protocol, and binary application protocol our custom, rather than on the visible character or JSON assembly flow of information. But we want to see is something like this information "0A 53 49 B7 FC 2E".

  These binary data directly if the print function print (), then in the console to see is a lot of character in the form of byte values ​​represented see is garbled. If you use Python in the hex () function turn it over and then sequentially output, will come with "0x" characters in front of each, and 01 will be printed as 1, looks very irregular, chaotic feeling, and print time to artificially add a space after each byte to byte separately.

  After practice, we can format the output value becomes the byte hexadecimal character, then join () function output, you can achieve the effect we want, and want to print string ASCii value can, but first with the ord () function turn about, the following two functions I are packaged, respectively, and strings of bytes type output debugging purposes only.

Byte type of print:

# 字节列表以16进制格式打印数据
def print_bytes_hex(data):
    lin = ['%02X' % i for i in data]
    print(" ".join(lin))

# 测试字节列表,这也是网络传输收到的原始类型
arr = [0x4B, 0x43, 0x09, 0xA1, 0x01, 0x02, 0xAB, 0x4A, 0x43]
print_bytes_hex(arr)

'''
控制台输出:
4B 43 09 A1 01 02 AB 4A 43
'''

Print string type:

# 字符串或字符列表以16进制格式打印数据
def print_string_hex(data):
    lin = ['%02X' % ord(i) for i in data]
    print(" ".join(lin))

# 测试字符串类型
arr = 'Work'
print_string_hex(arr)

'''
控制台输出:
57 6F 72 6B
'''

  If we are to develop the Internet of Things project, involving signaling need to communicate with hardware developers when there are basically hardware described in hexadecimal, so the output format of uniform data stream format on the server side to facilitate the exchange of .

  The above can be achieved with a print circulation (formatting and processing spaces during printing) to achieve, but to write a bit bloated, but do not generate a new list, occupy favorable instant memory (sorry, hardware write the code to leave the habit always think of memory footprint, because it limited resources MCU) based on this we can improve ourselves.

Guess you like

Origin www.cnblogs.com/xueweisuoyong/p/11841132.html