I have some byte data (say for an image):
00 19 01 21 09 0f 01 15 .. FF
I parse it and store it as a byte list:
[b'\x00', b'\x19', b'\x01', b'\x21', b'\x09', b'\x0f', b'\x01', b'\x15', ...]
These are RGBA values (little endian, 2 bytes) that I need to parse as dict format as follows:
[{'red':0x0019, 'green':0x2101, 'blue':0x0f09, 'alpha':0x1501}, {'red':...},...]
Note: The image data terminates once we reach a 0xff
. Values can be stored in hex or decimal, doesn't matter as long as it's consistent.
My attempt:
# our dict keys
keys = ['red', 'green', 'blue', 'alpha']
# first, grab all bytes until we hit 0xff
img = list(takewhile(lambda x: x != b'\xFF', bitstream))
# traverse img 2 bytes at a time and join them
rgba = []
for i,j in zip(img[0::2],img[1::2]):
rgba.append(b''.join([j,i]) # j first since byteorder is 'little'
So far it will output [0x0019, 0x2101, 0x0f09, ...]
Now I'm stuck on how to create the list of dicts "pythonically". I can simply use a for loop and pop 4 items from the list at a time but that's not really using Python's features to their potential. Any advice?
Note: this is just an example, my keys can be anything (not related to images). Also overlook any issues with len(img) % len(keys) != 0
.