Example for Displaying Binary
Suppose DIP Switch 1 is set to 0xFA. When PrintSwitch gets called, byVal will be equal to 0xFA.
In your loop, you should print out:
11111010
Or to break it down further:
|
Bit |
Status |
Action |
|
7 |
On |
Print a '1' |
|
6 |
On |
Print a '1' |
|
5 |
On |
Print a '1' |
|
4 |
On |
Print a '1' |
|
3 |
On |
Print a '1' |
|
2 |
Off |
Print a '0' |
|
1 |
On |
Print a '1' |
|
0 |
Off |
Print a '0' |
Thus, you need to test each bit. The only way to extract bits from a value is to use bit-wise operations. What bit-wise operator lets you test to see if bits are on or off?
| OR - Set
^ XOR - Toggle
& AND - Clear/Test
The bit-wise AND (&) allows you to test for individual bits. Why is this?
Value & 0 = Always 0
Value & 1 = The same value
In order to test for a bit, you can use the above properties of the AND operator. For the bit you want to test, AND it with 1 since anything ANDed with a 1 gives back the same thing. For the bits you don't want to test, AND with a 0 since anything ANDed with a 0 gives a zero.
Think of the bit-wise AND as a filter with the 1's allowing bits through and the 0's forcing the value to zero. Consider testing for bit 7 to see if it is true or false. The C code would look something like the following:
if(byVal
& 0x80)
{
/* Bit is on */
}
else
{
/* Bit is off */
}
