0

我有两个 char 8 位值,我需要将它们组合起来以构建一个短的 16 位值。

在 C++ 中,我会这样做:

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

我怎样才能在 Python v2.6.2 中做同样的事情?

看起来它在 Python 中是一样的,但我想确保没有一些细微的区别:

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

1 回答 1

1

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 :

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 ) .

于 2012-11-01T12:57:19.363 回答