簡體   English   中英

我不明白為什么我按位或short和char會得到這個結果

[英]I can't understand why I get this result when I bitwise OR a short and char

有人可以解釋為什么我按位或兩個數字時得到這個結果嗎? 我真的很困惑

signed char signedChar = -64;       // This is now -64, or 1100 0000
unsigned char unsignedChar = signedChar; // This is now 196, or 1100 0000 (The same)

short signedShort = 0;     // This is now 0000 0000 0000 0000
signedShort |= signedChar;   // This is now -64, not 196 

我期望發生的事情是,我簽署了signedShort和signedChar,這是:

0000 0000 0000 0000 or'ed with
          1100 0000
0000 0000 1100 0000 result 
equalling 196.

但是我得到了-64

為什么此OR操作在開始時添加一個? 我完全期望有所不同。

謝謝。

表達式signedShort |= signedChar; 被解釋為

signedShort = signedShort | signedChar;

|兩個操作數 將運算符提升為int ,對這些提升的值執行按位或運算,結果轉換為目標的類型short

因此, signedChar-64的值被擴展為具有相同值的int 或為0不會更改該值。 將其轉換為short也會保留該值,因為-64short范圍內,因此結果為-64

請注意,這不依賴於整數的實際表示。 您假設問題中有2s補碼,但是以正負號或1s補碼會產生相同的結果。

具有負值的帶符號類型將以1擴展。 無符號類型將以零擴展。

您未簽名的字符將被提升為已簽名,因為這就是您執行操作所要使用的字符。

已簽名是未簽名的促銷

在您的示例中:

0000 0000 0000 0000 or'ed with
1111 1111 1100 0000
1111 1111 1100 0000 result

基本上就是二進制補碼算法的工作原理。 為了保留值的符號,在轉換過程中將應用特殊的符號擴展

讓我們以-10的簡單示例為例:

signed char signedChar = -10; // bits: 11110110b
signed short signedShort = signedChar; // bits: 1111111111110110b

為什么不像您期望的那樣顯示1000000000000110b? 因為1000000000000110b是-32762的二進制補碼:-(

暫無
暫無

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

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