3

A byte of data can represent values from o to 255. However, when I declare a byte objct in python and give it an integer less than 255, the size is still huge.

>>a=b'9'
>>sys.getsizeof(a)
>>18
>>a=b'19'
>>sys.getsizeof(a)
>>19
>>a=b'019'
>>sys.getsizeof(a)
>>20

This data needs to go to an SPI device via the wiring-pi library for raspberry pi. The original C function which is wrapped in python by the library takes as input, a char array, which are perfectly byte sized. however, in python, the function takes a b'' as its argument. The message 'Hello World!\n' is 13 bytes if represented as a char array. declaring the string in python and encoding it with str.encode() gives an object that has a size of 30 byte.

>>s ='Hello World!\n'
>>s=s.encode()
>>sys.getsizeof(s)
>>30

How can I fix this such that '1' is a representation of the number '1' and has a size of one byte (represented as 00000001 bits), and that the string Hello world!\n is in fact an array of 13 bytes?

Adi
  • 75
  • 1
  • 9
  • 1
    You can't. Welcome to Python. `b'\x01'` – Ignacio Vazquez-Abrams Jul 26 '16 at 17:15
  • What does it matter if the actual object in memory is a few bytes larger than its contents? If you write it somewhere (a binary file, a pipe to another process, a serial port to a microcontroller, ...) you only write the actual content bytes (i.e., 13 bytes in the case of `b'Hello world!\n'`). – marcelm Jul 26 '16 at 22:35

0 Answers0