arrayspython-2.7type-conversiontftp

Python byte array to integer conversion (TFTP Client)


I am trying to set up a TFTP client using Python 2.7.
Problem is when I receive data packet, it is in the form of byte array of integers. For example: '\x03\x00\x01'. I want to convert each byte of byte array string to corresponding integer value.

I tried this method:

receiving_pack = '\x03\x00\x01'
int(receiving_pack[0], 16)

But I got following error message:

ValueError: invalid literal for int() with base 16: '\x03'

I tried another method:

struct.unpack(h, receiving_pack[0])[0]

But got error:

error: unpack requires a string argument of length 2

Solution

  • Convert to a bytearray and then index or iterate.

    >>> nums = bytearray('\x03\x00\x01')
    >>> nums[0]
    3
    >>> nums[1]
    0
    >>> nums[2]
    1