I have the following bytearray on Python
bytearray(b'\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n\')
and I want to conver the hexa values of the bytearray to an integer array of values converting the hexa to integer: x02cb00 to integer values for each '\n'. List just separe them each one. It should look like:
[183040, 183040, ... 183040]
How can I get it?
I did a list(bytarray) and it just worked for single values not composite ones.
CodePudding user response:
You can split the bytearray on newline and then map it to integers
xs = bytearray(b'\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n')
result = []
for line in xs.split(b'\n'):
result.append(int.from_bytes(line))
result[:-1]
since xs.split(b'\n')
return a list ending with bytearry(b'')
you should drop the last element.
CodePudding user response:
Try:
b = bytearray(b'\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n\x02\xcb\x00\n')
int_list = [int.from_bytes(n, "big", signed=False) for n in b.split(b'\n')[:-1]]
print(int_list)
Output:
[183040, 183040, 183040, 183040]
Just be careful about the endianess ["big", "little"]
and the sign.