簡體   English   中英

如何在 c++ 中將兩個無符號字符合並為一個無符號短(16 位)

[英]How to merge two unsigned chars into a single unsigned short(16 bits) in c++

如何在 c++ 中將兩個無符號字符合並為一個無符號短字符。 數組中的最高有效字節包含在數組[0] 中,最低有效字節位於數組[1] 中。 (大端)

(array[0] << 8) | array[1]

請注意,當您將unsigned char用於任何計算時,它會被隱式轉換(“提升”)為int 因此array[0] << 8不會溢出。 此計算的結果也是一個int ,因此如果您的編譯器發出警告,您可以將其轉換回 unsigned short 。

將short設置為最低有效字節,將最高有效字節移位8並執行二進制或操作以保持下半部分

unsigned short s;
s = array[1];
s |= (unsigned short) array[0] << 8;

暫無
暫無

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

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