Home > Net >  How to create bytes list in python?
How to create bytes list in python?

Time:12-22

I am facing a challenge to create a bytes list in python. I just want to convert the int list into bytes list as mentioned in expected result. The problem statement is that I want to send the expected output to the serial device connected to the com port and with current output the serial device is not encouraging the '\\' as a separator. Please suggest me the correct way to handle the '\' in a list of bytes.

cmdlist = [2, 12, 1, 1, 1, 0, 0, 1, 3, 7, 42, 101, 85, 18]
    
#Convert CMD list to Hex List
for i in range(len(cmdlist)):
    cmdlist[i] = hex(cmdlist[i])

f_cmdList = ''
#Convert hex CMD list to string List
for i in range(len(cmdlist)):
    f_cmdList  = '\\'   (cmdlist[i])

Final_cmdlist = (bytes(f_cmdList,'utf-8'))
print(Final_cmdlist)

Current output : b'\\0x2\\0xc\\0x1\\0x1\\0x1\\0x0\\0x0\\0x1\\0x3\\0x7\\0x2a\\0x65\\0x55\\0x12'

Expected output : b'\0x2\0xc\0x1\0x1\0x1\0x0\0x0\0x1\0x3\0x7\0x2a\0x65\0x55\0x12'

Thank You !

CodePudding user response:

You can convert a list to bytes simply by using the bytes constructor. Your method is trying to create a string that contains the string representation of a byte array, which won't work when sent to the serial device:

>>> cmdlist = [2, 12, 1, 1, 1, 0, 0, 1, 3, 7, 42, 101, 85, 18]
>>> bytes(cmdlist)
b'\x02\x0c\x01\x01\x01\x00\x00\x01\x03\x07*eU\x12'

CodePudding user response:

You get what you say you expect if you replace your

f_cmdList  = '\\'   (cmdlist[i])

with this:

f_cmdList  = '\0'   cmdlist[i][1:]

Still not convinced that you really want that, though.

  • Related