char数组到unsigned char python

2024-10-01 04:49:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将这段c代码转换成python,但是我在char*到{}的转换中遇到问题:

void sendAsciiCommand(string command) {
    unsigned int nchars = command.length() + 1; // Char count of command string
    unsigned int nshorts = ceil(nchars / 2);    // Number of shorts to store the string
    std::vector<unsigned short> regs(nshorts);  // Vector of short registers

    // Transform char array to short array with endianness conversion
    unsigned short *ascii_short_ptr = (unsigned short *)(command.c_str());

    for (unsigned int i = 0; i < nshorts; i++)
         regs[i] = htons(ascii_short_ptr[i]);          

    return std::string((char *)regs.data());
}

我在Python2.7中尝试过以下代码:

^{pr2}$

但它给了我一个错误:

ValueError: string length not a multiple of item size

有什么帮助吗?在


Tags: ofto代码stringarraylengthcommandint
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:07

例外文本:

ValueError: string length not a multiple of item size

也就是说,您试图从中创建数组的字符串的长度必须是项大小的倍数。在本例中,项目大小为unsigned short,即2个字节。因此,字符串的长度必须是2的倍数。hello的长度为5,它不是2的倍数,因此不能从中创建2字节整数数组。如果字符串长度为6个字节,例如hello!,它就可以工作。在

^{pr2}$

您可能仍然需要转换为网络字节顺序。array使用机器上的本机字节顺序,因此如果本机字节顺序是little-endian,则需要将其转换为big-endian(网络字节顺序)。如果需要,请使用sys.byteorder进行检查,并使用array.byteswap()交换字节顺序:

import sys
from array import array

s = 'hello!'
regs = array('H', s)
print(regs)
# array('H', [25960, 27756, 8559])
if sys.byteorder != 'big':
    regs.byteswap()
print(regs)
# array('H', [26725, 27756, 28449])

但是,如果需要,使用^{}将直接转换为网络字节顺序更容易:

import struct

s = 'hello!'
n = len(s)/struct.calcsize('H')
regs = struct.unpack('!{}H'.format(n), s)
print(regs)
#(26725, 27756, 28449)

如果您真的需要array

regs = array('H', struct.unpack('!{}H'.format(n), s))

<> P>也值得指出的是,C++代码中包含错误。如果字符串长度为奇数,则会在字符串末尾读取额外的字节,并将其包含在转换后的数据中。额外的字节将是\0,因为C字符串应该以null结尾,但是最后一个unsigned short应该被忽略,或者您应该检查字符串的长度是否是{}的倍数,就像Python一样。在

相关问题 更多 >