25

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

unsigned char c = 0xFF;

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

0

3 Answers 3

30

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).

Sign up to request clarification or add additional context in comments.

Comments

0

The answer depends on python version.

$ python3
Python 3.6.8 (default, May  6 2020, 12:04:35) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> myba = bytes([0])
>>> myba[0]
0
>>> 
$ python 
Python 2.7.5 (default, Mar 20 2020, 17:08:22) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> myba = bytes([0])
>>> myba[0] 
'['
>>> 

Comments

0

The answer depends on the python version.

$ python 
Python 2.7.5 (default, Mar 20 2020, 17:08:22) ...
>>> myba = bytes([0])
>>> myba[0] 
'['
>>> myba = bytearray([0])
>>> myba[0]
0
>>> 
$ python3
Python 3.6.8 (default, May  6 2020, 12:04:35) ...
>>> myba = bytes([0])
>>> myba[0]
0
>>> myba = bytearray([0])
>>> myba[0]
0
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.