Python 3 Building an array of bytes

后端 未结 6 739
终归单人心
终归单人心 2020-12-29 01:44

I need to build a tcp frame with raw binary data, but all examples and tutorials I\'ve found talking about bytes always involve conversion from a string, and that\'s not wha

6条回答
  •  Happy的楠姐
    2020-12-29 02:16

    Here is a solution to getting an array (list) of bytes:

    I found that you needed to convert the Int to a byte first, before passing it to the bytes():

    bytes(int('0xA2', 16).to_bytes(1, "big"))
    

    Then create a list from the bytes:

    list(frame)
    

    So your code should look like:

    frame = b""
    frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
    frame += bytes(int('0x01', 16).to_bytes(1, "big"))
    frame += bytes(int('0x02', 16).to_bytes(1, "big"))
    frame += bytes(int('0x03', 16).to_bytes(1, "big"))
    frame += bytes(int('0x04', 16).to_bytes(1, "big"))
    bytesList = list(frame)
    

    The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.

提交回复
热议问题