4

I need to convert a byte array to a string to send to an SPI device.

Is there a more efficient way of doing this ?

def writebytes(bytes):
  str = ""
  for i in bytes: str += chr(i)
  self.spi.transfer(str) 
0

1 Answer 1

5

Use "".join with a generator expression.

def writebytes(bytes):
    self.spi.transfer("".join(chr(i) for i in bytes))
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, using generator expression is slower than using simple "".join(map(char, bytes)) because when a generator expression is passed, join has to iterate over the results to get the total length of input and save them for later. When passing a list, the elements will be available anytime.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.