[英]Why does Python remove leading zeroes when converting from string to int?
[英]Remove Leading Zeroes from struct in Python
我正在使用Python通過Beagle Bone進行串行通信。 我需要以十六進制格式傳輸數據。 所以我使用了這樣的struct
:
import Adafruit_BBIO.UART as UART
import serial
import struct
UART.setup("UART1")
ser = serial.Serial(port='/dev/ttyO1', baudrate = 19200)
print ser.portstr
ser.open()
tx_hex = 0x1234
tx_str = struct.pack('!I', tx_hex)
if ser.isOpen():
print "Serial is open!"
ser.write(tx_str)
else:
print "Serial is closed!"
ser.close()
但是,我收到00 00 12 34
(十六進制),而我希望它只是12 34
。 如何擺脫前導零?
對struct
使用不同的格式:
tx_str = struct.pack('!H', tx_hex)
另請參見https://docs.python.org/2/library/struct.html#format-characters
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.