简体   繁体   中英

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.

In C++, I would do it like this:

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

How can I do likewise in 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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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