如何在python中生成raw_input()十六进制的返回值?

时间:2012-10-17 08:57:34

标签: python serial-port hex

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)

2 个答案:

答案 0 :(得分:1)

使用以下一个班轮,==example

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

长形式是:

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

答案 1 :(得分: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