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) 
crankshaft
  • 2,607
  • 4
  • 45
  • 77

1 Answers1

5

Use "".join with a generator expression.

def writebytes(bytes):
    self.spi.transfer("".join(chr(i) for i in bytes))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    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. – Maciej Gol Oct 20 '15 at 19:10