简体   繁体   中英

Python: How Can I Convert Hexadecimal Characters to CType Data Types (e.g., uint32_t, uint16_t, etc.)?

Does anyone know a way to convert a string of hexadecimal characters into particular ctype variables?

To elaborate, I need create a function which takes in a hexadecimal list of characters and a string representing the datatype and produces a value according to the datatype specified.

I am parsing MAVlink fields whose values take on data types of: uint64_t, uint32_t, int32_t, uint16_t, int16_t, uint8_t, int8_t, float, char

Additionally, the values of the fields can be arrays of the above types.

This is what my function looks like now:

    def getValue(payload, ftype):
        #  Check if signed or unsigned
        if ftype.find("uint") != -1: signed = False
        #  Check size of data type
        if   ftype.find('int8_t') != -1: stride = 1
        elif ftype.find('int16_t') != -1: stride = 2
        elif ftype.find('int32_t') != -1: stride = 4
        elif ftype.find('float') != -1: stride  = 4
        else: stride = 1 (Assume characters)
        chars = []
        while(stride > 0):
            #  Pop two characters to get one byte
            chars.append(payload.pop(0))
            chars.append(payload.pop(0))
            stride -= 1
        #  Convert selected characters to value of specified data type
        return convertToValueAsString(chars, ftype) #  I don't know how to do this

I've take a look at ctypes and using ctypes.uint*_t.value(a). However, I'm not sure how to use this function when the data type is a string and not a known value.

Use struct module.

import struct
payload = b'\x00\x7d\x00\x00\x01\x00\x00\x00'
format_ = 'Hxxb'
bytelen = struct.calcsize(format_)  # Value is: 5
print(struct.unpack(format_, payload[:bytelen]))  # (32000, 1)
print(struct.pack(format_, 32000, 1))  # b'\x00}\x00\x00\x01'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM