Home > Software design >  'bytes' object cannot be interpreted as an integer
'bytes' object cannot be interpreted as an integer

Time:09-22

I have a code piece which reads from socket and appends all bytes to an array (this is how it supposed to be work) but when I execute the code below:

def receiveData:
     bytemessage = bytearray()
     while True:             
           b = s.recv(1)
           logger.info(str(b))    
           bytemessage.append(b)

I am getting this error at the line where 'bytemessage.append(b)'

'bytes' object cannot be interpreted as an integer Example

I can log all the bytes I read from socket and all of them is in byte format like this b'\x01' Does anyone have a solution proposal ?

CodePudding user response:

From the docs, bytearray is a mutable sequence of integers in the range 0 <= x < 256. You can only append an integer in that range. A bytes object is an immutable array of integers in the same range. So you can do

bytemessage.append(b[0])

But you can also extend bytearray, which is convenient if you have a bytes object with more than one byte. This also works

bytemessage.extend(b)

This will be more space efficient than creating a list of byte objects can combining them at the end. Personally, I would extend even if adding only a single byte as I think the syntax is less cluttered.

CodePudding user response:

From the docs

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256.

It's not meant to be container of generic byte objects.

You can add all the parts to a regular list and then join them all together instead

def receiveData():
    parts = []
    while True:             
        b = s.recv(1)
        logger.info(str(b))    
        parts.append(b)
    return b''.join(parts)
  • Related