2

I have 2 files which I am reading as bytes, I have another hardcoded 64 bytes array which I need to manipulate later.

 temp_list = []
    open_file_to_list(file_name1, temp_list)
    open_file_to_list(file_name2, temp_list)
    for byte_i in harcoded_arr: #byte_i is really an int
        temp_list.append(byte_i)

In order to create the hardcoded array I used bytearray but when I iterate over it, it is iterates as integers and not as bytes.

I would like to append the byte array as bytes to the list.

  harcoded_arr= bytearray(64)
  harcoded_arr[61] = 1
  harcoded_arr[62] = 1
  harcoded_arr[63] = 1

How can I iterate it the bytearray as bytes using Python 3.8

Gilad
  • 6,437
  • 14
  • 61
  • 119

1 Answers1

2

You could slice the bytes object to get 1-length bytes objects

harcoded_arr = bytearray(64)
harcoded_arr[61] = 1
harcoded_arr[62] = 1
harcoded_arr[63] = 1

for i in range(len(harcoded_arr)):
    print(harcoded_arr[i:i+1])

Output

bytearray(b'\x00')
bytearray(b'\x00')
bytearray(b'\x00')
.................
bytearray(b'\x01')
bytearray(b'\x01')
bytearray(b'\x01')

PEP-467 proposes that bytes and bytearray gain an optimized iterbytes method that produces length 1 bytes objects rather than integers

>>> tuple(b"ABC".iterbytes())
(b'A', b'B', b'C')

For more you can also go through this answer

mhhabib
  • 2,975
  • 1
  • 15
  • 29