### Using the bit-wise operators in C

• Using the bitwise operators

• The bit-wise operations are typically used do the following:

 Set a certain bit in a byte, short, int, or long variable Clear a certain bit in a byte, short, int, or long variable Flip a certain bit (0 ⇒ 1 or 1 ⇒ 0) in a byte, short, int, or long variable Test a certain bit in a byte, short, int, or long variable

• Note:

 The bit-wise operations often use a certain bit pattern (or bit mask) The bit pattern can often be expression more easily using different number systems We will also look at how to express a value in different number system in C

• Setting a certain bit in a bit pattern

• Set a certain bit in a bit pattern

• Suppose the variable a contains a bit pattern:

 ``` a = 1010...x...1101 ```

• Problem:

 Set the bit x to the value 1 without changing all other bits in the pattern.

• We can set the bit x inside the bit pattern to 1 using the OR operation with the following specific pattern:

 ``` a = 1010...x...1101 0000..010..0000 OR --------------- 1010...1...1101 ```

• Example: set the 2nd bit and the 4th bit in a bit pattern

 ``` int main( int argc, char* argv[] ) { char a = 0; /* 0 = 00000000 */ /* Bit pos: 76543210 */ a = a | 4; /* 16 = 00000100 - set 2nd bit */ a = a | 16; /* 16 = 00010000 - set 4th bit */ printf( "a = %d\n", a ); } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link and save in a scratch directory To compile:   gcc bit-op2.c To run:          ./a.out

• Observation: we need a better way to make bit patterns

• Fact:

 The decimal number system is terrible for expression a bit pattern

• Solution:

 Use different number systems !!!