[英]Type conversion: signed int to unsigned long in C
我目前正在學習C編程語言(K&R)的第二章,並了解按位運算。
這是激發我好奇心的例子:
x = x & ~077
假設一個16位字長和32位長型 ,我認為會發生的是077首先會被轉換為:
0000 0000 0011 1111 (16 bit signed int).
然后將其補充為:
1111 1111 1100 0000.
我的問題是,對於不同的x類型,接下來會發生什么? 如果x是一個有符號的int,則答案很簡單。 但是,如果x是一個有符號的長整數,我假設〜077將變為:
1111 1111 1111 1111 1111 1111 1100 0000
以下2s補碼以保留符號。 它是否正確?
同樣,如果x是一個無符號的long,則〜077將變為:
0000 0000 0000 0000 1111 1111 1100 0000
或者,將〜077首先轉換為簽名長整型:
1111 1111 1111 1111 1111 1111 1100 0000
...之后將其轉換為無符號長整數(位無變化)?
任何幫助都會幫助我弄清楚此操作是否總是將最后6位始終設置為零。
無論選擇哪種數據類型, ~077
都會將最右邊的6位設置為0
,將所有其他6位設置為1
。
假設有16位int
和32位long
,則有4種情況:
情況1
unsigned int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
unsigned long y = ~x; // y = 0000 0000 0000 0000 1111 1111 1100 0000
情況二
unsigned int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
long y = ~x; // y = 0000 0000 0000 0000 1111 1111 1100 0000
情況3
int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
unsigned long y = ~x; // y = 1111 1111 1111 1111 1111 1111 1100 0000
案例4
int x = 077; // x = 0000 0000 0011 1111
x = ~x; // x = 1111 1111 1100 0000
long y = ~x; // y = 1111 1111 1111 1111 1111 1111 1100 0000
在這里查看代碼。 這意味着在對源進行signed
時便完成了符號擴展。 當源為unsigned
,不擴展符號位,並且將左位設置為0
。
x = x & ~077 //~077=11111111111111111111111111000000(not in every case)
~077 is a constant evaluated at the complie time so its value will be casted according to the value of x at the compile time
因此AND操作將始終將x的最后6位轉換為0,其余位將保持不變在AND運算之前。 喜歡
//let x=256472--> Binary--> 0000 0000 0000 0011 1110 1001 1101 1000
x = x & ~077;
// now x = 0000 0000 0000 0011 1110 1001 1100 0000 Decimal--> 256448
因此,在編譯期間,不管數據類型如何,最后6位都將變為0,其余位保持不變。 並以knr The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.
寫在The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.
〜077是The portable form involves no extra cost, since ~077 is a constant expression that can be evaluated at compile time.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.