csapp 2.2.5 Signed versus Unsigned in C
2.2.5 Signed versus Unsigned in C
- C supports both signed and unsigned arithmetic for all of its integer data types.
- most numbers are signed by default.
- Adding charchter
'U'
or'u'
as a suffix creates an unsigned constant - C allows conversion between unsigned and signed
- most systems follow the rule that the underlying bit representation does not change(这里意思是底层的表示不变,那么怎么表示就是看是有符号还是没有符号)
- unsigned \(\rightarrow\) signed \(U2T_w\)
- signed \(\rightarrow\) unsigned \(T2U_w\)
(w is the number of bits for the data type)
Conversions can happen due to explicit(显式) casting:
int tx, ty;
unsigned ux, uy;
tx = (int) ux;
uy = (unsigned) ty;
happen implicitly:
int tx, ty;
unsigned ux, uy;
tx = ux; /* Cast to signed */
uy = ty; /* Cast to unsigned */
print a value of type int with directive %u
and a value of type unsigned with directive %d
:
int x = –1;
//0x8000 0000
unsigned u = 2147483648; /* 2 to the 31st */
printf(“x = %u = %d\n”, x, x);
printf(“u = %u = %d\n”, u, u);
//answer
x = 4294967295 = –1
u = 2147483648 = –2147483648
-8的补码1000
signed + unsigned \(\rightarrow\) unsigned + unsigned (implicity)
example:
#include<bits/stdc++.h>
using namespace std;
int main ()
{
printf("%d",(-1<0U));
return 0;
}
Consider the comparison –1 < 0U
,the second operand is unsigned.the first one is implicitly cast to unsigned. so the expression is equivalent to the comparison 4294967295U < 0U