0

I'm new to python programming but experienced in C. I can't figure out what the equivalent to a char in python is. From what I read there isn't one. A "char" in python is a one character string. In fact it might even be more than 1 byte if its unicode. I need to create a packet of data using bytes (read chars) that's say 128 bytes long and may contain nulls. I then want to write that packet to a serial port as a series of bytes not a string.

Whats the python equivalent of:

char buffer[128];
buffer[12] = '0x04'
buffer[15] = '0x00'
    ...etc
dpetican
  • 771
  • 1
  • 5
  • 12

1 Answers1

3

You're assuming the mixup between a character and a byte in C will carry over to Python. It doesn't. Strings are strings and numbers are numbers. There's still a bit of mixup in python2, but python3 makes them completely separate (bytes and str).

It's probably best if you get rid of that assumptions and start from what you want to achieve. You're essentially trying to generate an array of bytes with specific values. You can do that in (at least) two ways:

  1. Create a bytes object by converting a list of numbers: bytes([0x04, 0x00, ...]). Or joining byte strings together: b'\x04\x00' + b'\x....'.

  2. Create whole packet from a defined schema using the struct module. For example struct.pack("cccc", 0x04, 0x00, ...)

viraptor
  • 33,322
  • 10
  • 107
  • 191
  • Thanks. Thats helpful including the pointer above to binary buffers. But just to be pedantic doesn't python carry on (or even extend actually) the confusion by calling an array of bytes a byte string? To me a string is a null terminated array of... you guessed it chars lol – dpetican May 04 '16 at 01:02
  • Since python3 these are officially "bytes objects". The bytes string was my slip up, not official naming. (https://docs.python.org/3.5/reference/datamodel.html#the-standard-type-hierarchy) It's just strings in python2 because it mashes them together ("Characters represent (at least) 8-bit bytes.") I fixed the answer. – viraptor May 04 '16 at 01:08