Python bytearray()

The bytearray() method returns an array of bytes.

Syntax

bytearray(]])

source - source to initialize the array of bytes
  • string – Converts the string to bytes using str.encode()
  • integer – Creates an array of provided size, all initialized to null
  • iterable – Creates an array of size equal to the iterable count . Iterable integers must be between 0 <= x < 256
  • Without an argument an array size will be set to 0
encoding - if the source is a string, the encoding of the string. Ex. utf-8,ascii
errors - action to take when the encoding conversion fails

Examples

byte array from string

s = "String example"

ex = bytearray(s, 'ascii')
print(ex)

Output

bytearray(b'String exapmle')

Creating byte array from integer

#integer creates array of 3
i = 3

ex = bytearray(i)
print(ex)

Output

bytearray(b'\x00\x00\x00')

Creating byte array from iterable list

list = [1,2,3]

ex = bytearray(list)
print(ex)

Output

bytearray(b'\x01\x02\x03')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s