Skip to content
Advertisement

How to convert a binary data into c_ubyte_Array_64 in python

How to convert ` b’x00x00x00x00x00x00x00x01′ c_ubyte_Array_64 in python. I could find any resources only so any help would really appreciated.

I have to send this message which should be of type c_ubyte_Array_64

import ctypes
messages = {
    "RESET": b'x00x00x00x00x00x00x00x01',
}

ba = bytearray(messages['RESET'])

I tried it in the above manner but it gives me this error

TypeError: expected c_ubyte_Array_64 instance, got bytearray

Advertisement

Answer

Listing [Python.Docs]: ctypes – A foreign function library for Python.

>>> import ctypes as ct
>>>
>>> messages = {
...     "RESET": b"x00x00x00x00x00x00x00x01",
... }
>>>
>>> UByteArr64 = ct.c_ubyte * 64  # Create the array type
>>>
>>> arr = UByteArr64(*messages["RESET"])  # Create an array instance (by unpacking the byte sequence)
>>>
>>> arr
<__main__.c_ubyte_Array_64 object at 0x0000015C81D74C40>
>>> arr[0:16]
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
>>>
>>>
>>> # Or, in one line:
>>> (ct.c_ubyte * 64)(*messages["RESET"])
<__main__.c_ubyte_Array_64 object at 0x0000015C81DBA240>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement