0

python 将 raw_iput 中的值作为字符串返回。我希望将这些字符串转换为十六进制字符。所以:

 example = '\x05\x06\x40\x00\x02\x05'
 tx = raw_input("\nTX: ") #user enters 05 06 40 00 02 05

我该怎么做那个 tx == 例子?

到目前为止我的代码:

import base64
import serial
import crcmod
import binascii

s_port = 'COM1'
b_rate = 2400

#method for reading incoming bytes on serial
def read_serial(ser):
    buf = ''
    while True:
        inp = ser.read(size=1) #read a byte
        buf = buf + inp #accumalate the response
        if '\xff' == inp: #if the incoming byte is 0xff
            print buf.encode("hex") # never here
            break
    return buf.encode("hex")   


#method to calc the checksum            
def calc_crc(hstr):
    crc16 = crcmod.predefined.mkCrcFun('crc-16')
    hstr = hstr.replace(' ','')
    data = base64.b16decode(hstr)
    chsum = hex(crc16(data))
    return chsum

#create a serial opening
ser = serial.Serial(
    port=s_port,
    baudrate=b_rate,
    timeout=0.1
)

while True:
    example = '\x05\x06\x40\x00\x02\x05\xF6\x5C' #last 2 bytes are CRC
    tx = raw_input("\nTX: ") #user enters 05 06 40 00 02 05
    crc = calc_crc(tx) #checksum is calculated as 0xf65c, correct
    tx = binascii.hexlify(tx.replace(' ', '')) #convert ascii string into hex as is but how???????????
    print tx  #gives me 303530363430303030323035
    cmd = tx + crc # concatenate tx and crc so the command is complete
    ser.write(cmd)
    rx = read_serial(ser)
    print "RX: " + str(rx)
4

2 回答 2

1

使用以下一个衬里,我得到 True ==example

''.join([chr(int(x,16)) for x in tx.split()])

长格式是:

按空格拆分输入,并通过迭代拆分的输入来创建一个列表,并将输入中的每个数字转换为相对于基数 16 的 int,并将生成的 int 转换为带有 chr 的相应字符。最后将字符列表连接到一个字符串中。

于 2012-10-17T09:05:56.703 回答
1

尽管 OP 使用 Python 2.x,但在 Python 3中有一个内置方法bytes.fromhex可以做到这一点:

example = b'\x05\x06\x40\x00\x02\x05'
tx = input("\nTX: ")
result = bytes.fromhex(tx)
assert result == example
于 2012-10-17T10:44:41.763 回答