Convert Bytearray into List using list() - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Convert Bytearray into List using list() (/thread-32560.html) |
Convert Bytearray into List using list() - Shlok - Feb-18-2021 Following is code for creating list from bytearray with proper indexing using list: P.S.: Code can be small but I have inserted debug statements like print(), type(), etc. for understanding purpose my_list = b'[1, 0, 1, 1]' my_list_conv = list(my_list) print("Element at 0th index in my_list_conv = {}".format(my_list_conv[0])) print("Elements in my_list_conv:") for values in my_list_conv: print(chr(values) , end=" ") print("\nASCII converted element at 1st index: {}".format(chr(my_list_conv[1]))) print(type(my_list_conv)) ### Not a proper list i.e. indexing is not proper new_list = [] ### Created new_list for copying data for proper indexing for x in my_list_conv: if (chr(x) == '1') or (chr(x) == '0'): new_list.append(chr(x)) print(new_list) print(type(new_list)) print(new_list[1]) print(type(my_list)) Following will be output for this program:
RE: Convert Bytearray into List using list() - Gribouillis - Feb-18-2021 Is there a question? RE: Convert Bytearray into List using list() - deanhystad - Feb-18-2021 What is the application for this? About the only time I run into byte arrays is serial ports or sockets. For those applications I would send an array of bytes as an array of bytes, not an array of ASCII codes for bytes. If I was sent an array of bytes encoded like this I would probably use decode() to convert the bytearray to a string, and then process the string. This converts your bytearray to an array of ints. my_list = b'[1, 0, 1, 1]' my_bin_nums = [int(c) for c in my_list.decode() if c in '01'] print(my_bin_nums, my_bin_nums[1])
|