I am trying to convert a c_byte array into different datatypes in Python, e.g. converting a eight-entry c_byte array into a int64 or double.
In my project, I read a long c_byte array (n>500) containing multiple sensor values with different datatypes. So maybe the first entry is a bool, the second and third entry represent a int8 and entries 4-11 store a double. I am looking for a convenient way of casting those array-entries into the required datatypes.
At the moment, I am transcribing the byte-array into strings containing the binary number. I was thinking about manually writing functions to convert those strings into floats and ints, but I hope there is a more elegant way of doing so. Also, i run into problems converting signed ints...
def convert_byte_to_binary(array):
binary = ''
for i in array:
binary += format(i, '#010b')[2:]
return binary
def convert_binary_to_uint(binary):
return int(binary, 2)
array = read_cbyte_array(address, length) # reads an array of size length, starting at address
array
[15, 30, 110, 7, 65]
convert_byte_to_binary(array)
'0000111100011110011011100000011101000001'
I found the bitstring library, which does something very similar to what I want. Unfortunately, I did not find any support for 64bit integers or double floats.
Ideally, I would have a set of function that can convert the ctypes.c_byte-array into the corresponding ctypes-types.