Python bytearray append bytes

Convert Bytearray to Bytes in Python

Many different types of data objects are supported by Python. Two of them are the objects bytearray and bytes. The bytearray() function returns an array object of bytes. This object is changeable and supports the integer number from 0 to 255. The bytes() function returns bytes objects, is not changeable, and supports the integers from 0 to 255. This article will describe these functions and explain how bytearray objects can be converted into bytes objects.

Syntax of bytearray() Method

The three arguments of this method are optional. The first argument is used to initialize the list of bytes. If the first argument is the string, then the second argument is used for encoding. Finally, the third argument is used to display the error if the encoding fails.

Syntax of bytes() Method

All arguments of the bytes() function are optional, like the bytearray() method. The functions of these arguments are also the same as the bytearray() method, mentioned above.

The method for converting bytearray to bytes in Python is shown below, using some simple examples for better understanding of this process.

Example 1: Convert List Data from bytearray to bytes

When the bytearray() function contains only one argument, the value of the argument will be a dictionary datum or variable. The following example shows how a dictionary object can be converted into a bytearray object and how a bytearray object can then be converted into a byte object. Next, the first for loop is used to display the values of the translation table of ASCII codes and the second for loop is used to display the characters of the corresponding ASCII codes.

# Define the list
listdata = [ 72 , 69 , 76 , 76 , 79 ]
# Print the content of the list
print ( » \n The dictionary values are : \n » , listdata )

# Initialize bytearray object with list
byteArrayObject = bytearray ( listdata )
# Print bytearray object value
print ( » \n The output of bytearray() method : \n » , byteArrayObject )

Читайте также:  User home page php

# Convert the bytearray object into bytes object
byteObject = bytes ( byteArrayObject )
# Print bytes object value
print ( » \n The output of bytes() method : \n » , byteObject )

print ( » \n The ASCII values of bytes» )
# Iterate the bytes object using loop
for val in byteObject:
print ( val , ‘ ‘ , end = » )

print ( » \n The string values of bytes» )
# Iterate the bytes object using loop
for val in byteObject:
print ( chr ( val ) , ‘ ‘ , end = » )

The following output will appear after running the script. Here, 72, 69, 76, and 79 are the ASCII code of ‘H,’ ‘E,’ ‘L,’ and ‘O,’ respectively.

Example 2: Convert String Data from bytearray to bytes

The following example shows the conversion of bytearray objects to byte objects in string data. Two arguments are used in the bytearray() method of this script. The first argument contains the string value, while the second argument contains the encoding string. Here, ‘utf-8’ encoding is used to convert into a bytearray object. The decode() method is used in the script to convert the bytes objects into string data. The same encoding is used at the time of conversion.

# Take a string value
text = input ( «Enter any text: \n » )

# Initialize bytearray object with string and encoding
byteArrObj = bytearray ( text , ‘utf-8’ )
print ( » \n The output of bytesarray() method : \n » , byteArrObj )

# Convert bytearray to bytes
byteObj = bytes ( byteArrObj )
print ( » \n The output of bytes() method : \n » , byteObj )

# Convert bytes value into string using emcoding
print ( » \n The string values of bytes» )
print ( byteObj. decode ( «utf-8» ) )

The following output will appear after running the script.

Example 3: Convert Integer Data from bytearray to bytes

The previous examples show the conversion of bytearray and bytes based on dictionary and string data. This third example shows the conversion of bytearray into bytes based on the input data. Here, the input value is converted into an integer value and passed as an argument via the bytearray() function, and the bytearray object is then converted into a bytes object. The null values based on the integer number are shown as an output of the bytearray and bytes object. The total number of bytes is counted via the len() method at the end of the script, and will be equal to the integer value passed as an argument into the bytearray() method.

Читайте также:  Wait one second java

try :
# Take any number value
text = int ( input ( «Enter any number: » ) )

# Initialize bytearray object with number
byteArrObj = bytearray ( text )
print ( » \n The output of bytesarray() method : \n » , byteArrObj )

# Convert bytearray object to bytes object
byteObj = bytes ( byteArrObj )
print ( » \n The output of bytes() method : \n » , byteObj )

# Print the size of the bytes object
print ( » \n The lenght of the bytes object: » , len ( byteObj ) )
except ValueError :
print ( «Enter any numeric value» )

After running the script, 6 is taken as input in the following output. The six null values are displayed as the output of bytearray and bytes. When the null values are counted then it displayed 6.

Example 4: Create bytearray Using append() and Convert to bytes

The following example shows how bytearray objects can be created via the append() method and converted into bytes. The arrVal variable is declared here as a bytearray object. Next, the append() method is called six times to add six elements into the array. The ASCII codes of the characters, ‘P,’ ‘y,’ ‘t,’ ‘h,’ ‘o,’ and ‘n,’ are 80, 121, 116, 104, 111 and 1120, respectively. These are added in the bytearray object. This array object is converted into the bytes object later on.

# Create bytearray and add item using append() method
arrVal = bytearray ( )
arrVal. append ( 80 )
arrVal. append ( 121 )
arrVal. append ( 116 )
arrVal. append ( 104 )
arrVal. append ( 111 )
arrVal. append ( 110 )

# Print the bytearray() values
print ( » \n The output of bytearray() method : \n » , arrVal )

# Convert the bytearray object into a bytes object
byteObject = bytes ( arrVal )

# Print bytes object value
print ( » \n The output of bytes() method : \n » , byteObject )

The following output will appear after running the script.

Conclusion

Various methods are shown in this article for converting bytearray to bytes after creating bytearray objects. After reading this article, I hope that you understand the concept of bytearray and bytes, know the way to convert bytearray to bytes, and be able to display the output of bytes as string and characters.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Python ByteArray: Everything you need to know!

Embedded Inventor

In this article, let us learn about the ByteArray data structure in Python and learn how and when to use it in our Python programs.

Читайте также:  Вывод рандомных чисел java

For those of you in a hurry here is the short version of the answer.

ByteArray in a Nutshell

ByteArray is a data structure in Python that can be used when we wish to store a collection of bytes in an ordered manner in a contiguous area of memory.

ByteArray comes under binary data types.

You can use the bytearray() constructor to create a ByteArray object as shown below

>>> numbers = [1, 2, 3, 4] >>> myByteArray = bytearray(numbers) >>> print(myByteArray) bytearray(b'\x01\x02\x03\x04')

Here the syntax we have used is

bytearray(iterable_of_ints)

Depending on the type of data we wish to convert into an array of bytes, the ByteArray class gives us 4 different constructors are shown in the table below.

Type of Data Constructor
List of integers bytearray(iterable_of_ints)
Strings bytearray(string, encoding[, errors])
Bytes bytearray(bytes_or_buffer)
Empty Byte Array bytearray()
Empty Byte Array of a given size bytearray(int)

Examples of how to use each one are given further down in the article.

The table below shows the most commonly used methods in the ByteArray class

Method Meaning
append() Append a single item to the end of the bytearray
extend() Append all the items from the iterator or sequence to the end of the bytearray.
insert() Insert a given element at a specified index.
remove() Remove the first occurrence of a value in the bytearray.
pop() Remove and return a single item from B.
clear() Remove all items from the bytearray.
copy() Return a copy of the bytearray object
count() Return the number of non-overlapping occurrences of a given subsection in
bytearray
reverse() Reverse the order of the values in bytearray in place.
find() Return the lowest index where the given subsection is found.

Examples of how to use these above methods, along with some more useful methods are given later on in the article.

If the above answer feels insufficient do not worry as this section was meant to be a quick reference for those who are already familiar with the topic. Read on for a more complete answer where we have explained everything you need to know about ByteArrays with the help of examples!

Feel free to skip to your topic of interest using the table of contents below.

Источник

Оцените статью