As the name indicates bytearray is an object, which is an array of bytes. This array of bytes has got tremendous applications mostly in data manipulation. For example, while encoding, compressing, and mapping data byte arrays are used.
In the python bytearray()
function takes an object as input and can produce the corresponding byte array which is mutable.
bytearray(a, encoding, error) #where a can be an object or an integer
Takes 3 parameters where the first parameter can be an object and if the object is a string the encoding format to be specified as the second parameter.
Parameter | Description | Required / Optional |
---|---|---|
Value | The value can be an integer, string, or an iterable | Optional |
Encoding |
If the string is passed as a parameter, the string encoding to be specified | If the first parameter is a string then required |
Error | To specify what to be done on error | Optional |
The return value will be different based on the type of the parameter passed as input.
Input | Output |
---|---|
Integer | A byte array of the specified size initialized |
String as first parameter and encoding as the second parameter | The string encoded to bytes |
Iterable | Byte array as the same size as the iterable |
No parameter | Creates a byte array with no elements |
byte_array = bytearray(3)
print(byte_array)
Output:
bytearray(b'\x00\x00\x00')
string = "Happy!" print(bytearray(string, 'utf-8'))
Output:
bytearray(b'Happy!')
keys = {1 : ‘a’,2:’b’}
print(bytearray(keys))
Output:
bytearray(b'\x01\x02') When dictionary is passed its keys will be converted to bytearray