w3resource

Python program to convert list of integers to bytearray


3. Bytearray Creation from List

Write a Python program to create a bytearray from a given list of integers.

Sample Solution:

Code:

def  bytearray_from_list(int_list):
    byte_array = bytearray(int_list)
    return byte_array

def main():
    try:
        nums = [72, 123, 21, 108, 222, 67, 44, 38, 10]
        
        byte_array_result = bytearray_from_list(nums)
        
        print("Integer List:", nums)
        print("Bytearray:", byte_array_result)
        print("Decoded String:", byte_array_result.decode("utf-8"))
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Integer List: [72, 123, 21, 108, 222, 67, 44, 38, 10]
Bytearray: bytearray(b'H{\x15l\xdeC,&\n')
An error occurred: 'utf-8' codec can't decode byte 0xde in position 4: invalid continuation byte

Flowchart:

Flowchart: Python program to convert list of integers to bytearray.

For more Practice: Solve these Related Problems:

  • Write a Python program to create a bytearray from a list of integers and then modify one of its elements before printing.
  • Write a Python script to convert a list of integer values into a bytearray and then iterate over it to display each byte in hexadecimal.
  • Write a Python function that accepts a list of integers, converts it to a bytearray, and then appends additional integer values to it.
  • Write a Python program to generate a bytearray from a list of integers, reverse the bytearray, and then print the resulting bytes.

Python Code Editor :

Previous: Python program for concatenating bytes objects.
Next: Python Program: Read and modify image as bytes.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.