0

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
raja
  • 380
  • 2
  • 9
  • 20

3 Answers3

1

Your format string is incorrect. It must be in quotes (obvious) and the count of bytes it defines MUST match number of bytes in the byte string.

Use unpack to convert the byte string b'\x03\x00\x01' to integers,

Using Python 3.6:

>>>import struct
>>>i = struct.unpack('<BBB', b'\x03\x00\x01')
>>>print(i)
(3,0,1)

struct has been around since Python 2.7, so you shouldn't have a problem. The format string '

JackCColeman
  • 3,777
  • 1
  • 15
  • 21
0

The best method would be:

receiving_pack = '\x03\x00\x01'

to convert this to integers byte by byte:

map(ord, receiving_pack)
-> [3, 0, 1]
raja
  • 380
  • 2
  • 9
  • 20
0

Convert to a bytearray and then index or iterate.

>>> nums = bytearray('\x03\x00\x01')
>>> nums[0]
3
>>> nums[1]
0
>>> nums[2]
1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358