Programming Problems Using Structure 285
// bits . c1
# inc lude < stdio .h >2
# inc lude < stdlib .h >3
# inc lude < string .h >4
int main ( i nt argc , char * * argv )5
{6
unsigned char a = 129; // decimal 129 , he xadecima l 0 X817
unsigned char b = 0 XF0 ; // decimal 2408
unsigned char c = a & b ; // h exadecim a l 0 X80 , decimal 1289
printf (" %d , %X n" , c , c ); // 128 , 8010
unsigned char d = a | b ; // h exadecim a l 0 XF1 , decimal 24111
printf (" %d , %X n" , d , d ); // 241 , F112
unsigned char e = d << 3; // he xadecima l 0 X88 , decimal 13613
printf (" %d , %X n" , e , e ); // 136 , 8814
unsigned char f = d >> 2; // he xadecima l 0 X3C , decimal 6015
printf (" %d , %X n" , f , f ); // 60, 3C16
return EXIT _SUCCES S ;17
}18
The output of this program is:
128, 80
241, F1
136, 88
60, 3C
The final bit-wise operation that we will consider is the exclusive or operation, often
abbreviated as XOR. With XOR, the resulting bit is 1 if and only if the two input bits are
different from each other. Here is an illustrative example:
0 1 1 0 1 0 0 1
∧ 1 1 0 1 0 0 0 0
1 0 1 1 1 0 0 1
Please note that ∧ means exclusive or (XOR) in C programs. In some other languages, ∧
means exponential. C uses exp for exponential.
17.2.4 Inserting and Retrieving Decimal Digits
In DecPack, a decimal digital (0 to 9) requires only 4 bits. Thus, to put this digital into
the upper 4 bits, it needs to be shifted left by 4; 4 zeros will be added to the right 4 bits.
To retrieve one decimal digit from the upper 4 bits, the byte is shifted right by 4 bits; 4
zeros will be added to the left 4 bits. To put one decimal digital into the lower 4 bits, it can
be added to the byte. To retrieve one decimal digital from the lower 4 bits, a mask 0x0F is
used to block the upper 4 bits.
The indexes need to be carefully managed. The value of used means the number of
digits that have been already inserted. If used is an even number (for example, 8), then the
next inserted digit should be the 9
th
digit. In C programs, array indexes start from 0. The
9
th
digit uses the 5
th
byte and the index should be 4. The index is 8 / 2 (integer division).
Thus, used / 2 is the correct index. If used is an odd number (for example, 11), then the
next inserted digit is the 12
th
digit. It should be the 6
th
byte and the index is 5; used / 2
is also the correct index. Thus, used / 2 is the correct index for insertion; used should be
incremented after insertion.