You might need to learn about bit manipulations and binary numbers.
You may experiment first with paper and pencil:
- what is ther binary represntation of say 0, 1, 2, 3, 4, ..., 15?
- what do the the following operators: bit-and (&), bit-or (|), bit-xor (^), complement (~)?
Work with 4 bit values only to start with.
E.g. decimal 3 = binary 0011.
The right most binary digit has the factor 1, the next on the left is 2, then 4 and then 8.
This is analogous to decimal numbers: the right most is factor 1, then 10, then 100, etc.
Decimal: 1 = 10
0, 10 = 10
1, 100 = 10
2, etc.
Binary: 1 = 2
0, 2 = 2
1, 4 = 2
2, etc.
E.g. decimal 123 is 1x10
2 + 2x10
1 + 3x10
0 = 100 + 20 + 3
E.g. binary 1110 is 1x2
3 + 1x2
2 + 1x2
1 + 0x2
0 = decimal 8+4+2+0 = 14
For bit-operations: the operations are bitwise:
x & y: result bit is 1 if x==1 and y==1, 0 otherwise (bit-and)
x | y: result bit is 1 if x==1 or y==1, 0 otherwise (bit-or)
x ^ y: result bit is 1 if x!=y, 0 otherwise (bit-xor)
~x: result bit is 1 if x==0, 0 otherwise (complement)
E.g. decimal 6 & 3 = binary 0110 & 0011 = 0010.
You might prefer to write it this way:
6 = 0110
3 = 0011
& = 0010 the bits that are both 1 result in 1, all others in 0
So, your question on getting the lowest two bits only:
int a;
...
a = a & 3; ...
This results in all bits but the lowest two are always 0, and the lowest two bits are taken as-is.
Cheers
Andi