【问题标题】:python BCD format into Structpython BCD格式转换成Struct
【发布时间】:2021-12-03 18:59:00
【问题描述】:

我在 CPP 中有以下代码,我试图将其移植到 Python 以将数据发送到 UDPS

#define VERSION_MAIN                "V6.60"
#define VERSION_BIN_MAJOR           0x06
#define VERSION_BIN_MINOR           0x60

unsigned char temp[3];


temp[0] = VERSION_MAIN[0];
temp[1] = VERSION_BIN_MAJOR;
temp[2] = VERSION_BIN_MINOR;

我尝试过如下代码:

byteone = bytes(VERSION_MAIN, 'utf-8') 

hex_string = '0x06'
decimal_int = int(hex_string, 16)
decimal_string = str(decimal_int)
digits = [int(c) for c in decimal_string]
zero_padded_BCD_digits = [format(d, '04b') for d in digits]
s = ''.join(zero_padded_BCD_digits)

bytetwo = bytes(int(s[i : i + 8], 2) for i in range(0, len(s), 8))

hex_string = '0x60'
decimal_int = int(hex_string, 16)
decimal_string = str(decimal_int)
digits = [int(c) for c in decimal_string]
zero_padded_BCD_digits = [format(d, '04b') for d in digits]
s = ''.join(zero_padded_BCD_digits)

bytethree = bytes(int(s[i : i + 8], 2) for i in range(0, len(s), 8))

values = (byteonw,bytetwo,bytethree )
s= struct.Struct(f'!3B')
packed_data = s.pack(*values)

但我不断收到讨厌的错误

struct.error: required argument is not an integer

谁能帮帮我。

谢谢

【问题讨论】:

    标签: python struct


    【解决方案1】:

    V不用转成intpack也可以管理char类型。

    from struct import pack
    
    VERSION_MAIN = "V6.60"
    VERSION_BIN_MAJOR = 0x06
    VERSION_BIN_MINOR = 0x60
    
    version = pack("!c2B", VERSION_MAIN[0].encode('utf-8'), VERSION_BIN_MAJOR, VERSION_BIN_MINOR)
    
    # version = b'V\x06`'
    

    【讨论】:

    • 感谢这个人,使用它我还了解到我也在尝试对编码结构进行编码。上帝帮助我
    猜你喜欢
    • 2012-07-26
    • 1970-01-01
    • 2023-03-25
    • 2019-08-05
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多