Review of Intergers
Bits can represent set
1 | s = { 0 , 3 ,5 ,6} |
This representation is useful when we do File I/O.
bits operations can stand for set operation
bit operation set operation & Intersection | Union ~ Complement ^ Symmetric difference
Shift operation
shift operations always throw away the extra bits
Mapping between signed and 2’s complement number
Keep bit representation and reinterpret it
Constants in C
- by default considered to be signed values
- Unsigned if have “u”/“U” as suffix
1 | int a = 1; |
Expression evaluation
If there is a mix of signed and unsigned value in a single expression, signed value implicitly cast to unsigned
unsigned >= 0
is always true, don’t use this for loop condition1
2
3unsigned a = 0u;
printf("%u\n" , --a);
//42949672951
2//infinite loop
for (unsigned i = N - 1; i >= 0 ; i--) ;Proper way to use
unsigned
1
2
3
4unsigned i ;
for ( i = N - 1 ; i < N ; i--) ;
//break after i = 0
//Note that N shouldn't be negative signedSee more at Robert Seacord, Secure Coding in C and C++
Truncation signed numbers
Say that signed number x has bit representation of [xw−1,xw−2,….,x0]
x’, standing for truncated x to k bits, has the bit representation of [xk−1,xk−2,…,x0]
x=−xw−12w−1+xw−22w−2+…+x020
x′=−xk−12k−1+xk−22k−2+…+x020
xmod2k=xk−12k−1+xk−22k−2+x020
xmod2k−xk−12k=x′
Unfortunately, we can not determine xk−1 with a breeze, so after moduloing 2k
We first view interpret the bits as unsigned
, then convert it to signed
Division rounding
division should always round towards 0
A useful approximation
210=1024=1000=103
What is a ‘word size’ ?
the definition is ambiguous, you can just take it as the size of a pointer(address)
group x bits together as a word, x is a word size
Word oriented memory organization
address of successive words differ by 4(32 bits) or 8(64 bits)