简体   繁体   English

如何使用移位在Python中构建字符短缺?

[英]How to build a short out of char(s) in Python using bit shift?

I have two char 8 bit values that I need to combine to build a short 16 bit value. 我有两个char 8位值,需要将它们组合起来以构建一个短的16位值。

In C++, I would do it like this: 在C ++中,我会这样做:

unsigned char lower = <someValue>;
unsigned char upper = <anotherValue>;
unsigned short combined = lower + (upper << 8);

How can I do likewise in Python v2.6.2? 在Python v2.6.2中我该如何做?

It appears it will just be the same in Python, but I want to make sure there isn't some subtle difference: 看起来在Python中将是相同的,但是我想确保没有细微的差别:

lower = <someValue>
upper = <anotherValue>
combined = lower + (upper << 8)

It might be slightly overkill, but if you want to be really sure to avoid any hidden difference, I advise to fall back to C using ctypes : 这可能有点过大,但是如果您想确保避免任何隐藏的区别,我建议您使用ctypes退回到C:

lower = ctypes.cschar(<somevalue>)
upper = ctypes.cschar(<anothervalue>)
combined = ctypes.csshort( lower + (upper << 8) )

Doing so, you have the advantage of having hard-typed your variable, which will make debugging easier in the future. 这样做的好处是可以硬键入变量,这将使将来的调试更加容易。

NB : I'm not really sure if the << operator still works with ctypes ( there is no reason not to ) . 注意:我不太确定<<操作符是否仍适用于ctypes(没有理由不做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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