Overview:
The bytearray class in Python abstracts a sequence that holds a set of byte values. The bytearray is a mutable sequence.
The minimum value an element can assume in a bytearray is 0 and the maximum value is 255. In short it can hold ASCII range and the remaining 128 values. The difference between a bytes and a bytearray is that, a bytearray is a mutable sequence and a bytes is an immutable sequence.
Removal and replacement of an element or a slice is supported by the bytearray. The bytearray also supports extending it using its own elements or with the elements of another bytearray. A bytearray can be created using the constructor or using the fromhex() method. A bytearray is suitable to hold large number of integers in the range of 0-255.
Example: Default bytearray creation
|
# Example Python program that creates # Create an empty bytearray print("Length of an empty bytearray:") # Create an array of defined length print("A bytearray right after its creation:") print("Length of the bytearray:") # Replace the bytearray |
Output:
| Empty bytearray: bytearray(b'') Length of an empty bytearray: 0 A bytearray right after its creation: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') Length of the bytearray: 11 The bytearray after replacing its contents: b'Hello World' |
Example - Create bytearrays from text strings using different encodings:
|
# Example Python program that creates bytearrays # Created using ASCII encoding # Created using UTF-16 encoding # Created using UTF-32 encoding gmHebrew = "בּוֹקֶר טוֹב" |
Output:
|
Original string(in English): \x05\x00\x00\xb9\x05\x00\x00\xe7\x05\x00\x00\xb6\x05\x00\x00\xe8 \x05\x00\x00 \x00\x00\x00\xd8\x05\x00\x00\xd5\x05\x00\x00\xb9\x05 \x00\x00\xd1\x05\x00\x00') |
The UTF-16 and UTF-32 formats begin with the Byte Order Mark. In this example, the resultant bytearrays start with \xff\xfe which indicates that the data is in little endian format. For big endian format the Byte Order Mark will be \xfe\xff.
Example - Create bytearray from a string of hexadecimal values:
|
# Example Python program that creates a # Try creating a bytearray with three hexadecimal |
Output:
| Hexadecimal string: 041042043044 The bytearray created from a string of hexadecimal values: bytearray(b'\x04\x10B\x040D') Creating a bytearray with three hex values: 045046047 Traceback (most recent call last): File "/Users/vinodh/PythonProgs/ba_from_hex.py", line 16, in <module> ba = bytearray.fromhex(hexString) ValueError: non-hexadecimal number found in fromhex() arg at position 9 |
Creating a bytearray from a hexadecimal string requires the string to contain even number of hexadecimal values. Passing an odd number of hexadecimal values to the fromhex() method will result in an error stating that “non-hexadecimal number found in fromhex() arg” for the reason being a byte can store two hexadecimal values – each four bits of a byte stores one hexadecimal number each.