簡體   English   中英

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

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

我有兩個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)

這可能有點過大,但是如果您想確保避免任何隱藏的區別,我建議您使用ctypes退回到C:

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

這樣做的好處是可以硬鍵入變量,這將使將來的調試更加容易。

注意:我不太確定<<操作符是否仍適用於ctypes(沒有理由不做)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM