我试图将这段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
有什么帮助吗?在
例外文本:
也就是说,您试图从中创建数组的字符串的长度必须是项大小的倍数。在本例中,项目大小为
^{pr2}$unsigned short
,即2个字节。因此,字符串的长度必须是2的倍数。hello
的长度为5,它不是2的倍数,因此不能从中创建2字节整数数组。如果字符串长度为6个字节,例如hello!
,它就可以工作。在您可能仍然需要转换为网络字节顺序。
array
使用机器上的本机字节顺序,因此如果本机字节顺序是little-endian,则需要将其转换为big-endian(网络字节顺序)。如果需要,请使用sys.byteorder
进行检查,并使用array.byteswap()
交换字节顺序:但是,如果需要,使用^{} 将直接转换为网络字节顺序更容易:
如果您真的需要
array
:<> P>也值得指出的是,C++代码中包含错误。如果字符串长度为奇数,则会在字符串末尾读取额外的字节,并将其包含在转换后的数据中。额外的字节将是
\0
,因为C字符串应该以null结尾,但是最后一个unsigned short
应该被忽略,或者您应该检查字符串的长度是否是{相关问题 更多 >
编程相关推荐