Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a single byte variable in Python

Tags:

python

byte

How do we declare a single byte variable in Python? I would like to achieve the following result represented in C:

unsigned char = 0xFF;

I would like to know if it is possible to declare an 8-bit variable in Python.

like image 886
Papipone Avatar asked Dec 22 '16 02:12

Papipone


People also ask

How do you input byte in Python?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument. Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.


1 Answers

Python doesn't differentiate between characters and strings the way C does, nor does it care about int bit widths. For a single byte, you basically have three choices:

  1. A length 1 bytes (or bytearray) object mychar = b'\xff' (or mychar = bytearray(b'\xff'))
  2. An int that you don't assign values outside range(256) (or use masking to trim overflow): mychar = 0xff
  3. A ctypes type, e.g. mychar = ctypes.c_ubyte(0xff)

The final option is largely for dealing with C functions through ctypes, it's otherwise slow/not Pythonic. Choosing between options 1 and 2 depends on what you're using it for; different use cases call for different approaches (though indexing/iterating the bytes object would get you the int values if you need to use both forms).

like image 98
ShadowRanger Avatar answered Sep 28 '22 09:09

ShadowRanger