[Python] Efficiently extend a bytearray split into chunks?

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    Usually I have a bytearray with chunks of 4 bytes each (so when I want to split it into multiple uint32 later). Sometimes the bytearray is a chunk of 3 bytes each, which cannot be passed as easily into functions. I want to add an "empty" byte after every 3rd byte in the bytearray (efficiently, as there are around 1.000.000 bytes)

    Short term the problem is currently:

    data #(bytearray, data is either chunks of 3 bytes each or 4 bytes each)
    if buffer_size == 3: # already known
    pass # here it should extend the smaller bytearray with one empty byte
    new_array = np.frombytes(data, dtype=np.uint32) # work normal with 4 bytes, fails with 3 bytes
    val1, val2 = new_array//256, new_array%256


    Currently I avoid the problem altogether by splitting the bytearray into strings, but it runs rather slowly:

    new_array = np.array(data.hex(" ", buffer_size).upper().split(" "))
    new_array = np.vectorize(int)(new_array, 16)

    Continue reading...

Compartilhe esta Página