Linux Kernel Architecture

(Jacob Rumans) #1
Mauerer app03.tex V1 - 09/04/2008 6:11pm Page 1204

Appendix C: Notes on C


The program generates the following output:

wolfgang@meitner>./shift
count, val: 0, 1
count, val: 1, 2
count, val: 2, 4
count, val: 3, 8
count, val: 4, 16
count, val: 5, 32
count, val: 6, 64
count, val: 7, 128
count, val: 8, 256
count, val: 9, 512
count, val: 10, 1024

C provides a range of bitwise operators to link two numbers, which are listed in Table C-1. The~operator
is also available to apply bitwise NOT to the individual bits of a number.

Table C-1: Operations for Bitwise Linking of Two Numbers

Operator Meaning

& Bitwise ‘‘AND‘‘

| Bitwise ‘‘OR‘‘

^ Bitwise ‘‘Exclusive OR‘‘ (XOR)

These operations can be used to query and manipulate the individual bits of a bit string without recourse
to special assembler commands of the processor. However, such commands are occasionally used by
Linux to manipulate a bit string quickly or atomically. The general concept includes using a mask to
select a specific bit. In this mask, all bits are set to 0 and only the bit to be selected has the value 1. The
desired bit is selected by ‘‘ANDing‘‘ the mask with the actual number. The following example builds a
mask to help test the fifth bit of a bit string:

int main() {
int val1 = 33;
int val2 = 18;

int mask = 1;
mask <<= 4;

if (val1 & mask) {
printf("Bit 5 in val1 is set\n");
}

if (val2 & mask) {
printf("Bit 5 in val2 is set\n");
}
}
Free download pdf