# Bitwise Operators

Although this is not a C programming guide, you may not be familiar with bitwise operators. When working with embedded systems, it's very common to use these operators to manipulate the values inside the registers.

A bitwise operator is one that performs a logical operation on a pair of values bit by bit. For example, a bitwise AND operation on the values 0b1100 and 0b1010 would work as follows:

1 1 0 0 & 1 0 1 0 ------- 1 0 0 0

Bit 3 of the first value is ANDed with bit 3 of the second value, and so on.

## Bitwise AND

The bitwise AND operators (&) can be used to turn off specific bits in a register while leaving the rest alone. For example, if you want to turn off the ADIE bit (bit 6) in the PIE1 register without affecting the other options, you could do the following:

PIE1 = PIE1 & 0b10111111;

You can also use short hand:

PIE1 &= 0b10111111;

This works because all the other bits are being ANDed with a 1. So if that bit is a 1, it will stay a 1 and if that bit is a 0, it will stay a 0.

## Bitwise OR

The bitwise OR operator (|, called a 'pipe' which is typically SHIFT+backslash) performs an OR operation between bits. This is useful for turning on a specific bit without affecting the others. Let's turn on the ADIE bit in the PIE1 register:

PIE1 |= 0b01000000;

This works because the bit being ORed with a 1 will turn on no matter what the current value is. All other bits will be unaffected because they are ORed with a 0.

## Other Bitwise Operators

There is also a bitwise XOR (exclusive OR) operator (^, called a 'carat' which is shared with the 6 key). Finally, you can invert each bit in a value using the bitwise complement operator (~, called 'tilde' which is found by pressing SHIFT and the key to the left of 1).

## Shift Operators

You can shift the bits in a value to the left or the right. We saw this earlier when assembling the result from the ADC. TO shift to the left, the operator is << and to shift to the right, the operator is >>.

char test = 0b00011010 << 2; //test = 0b01101000

When shifting an unsigned data type to the left or right, the blank spaces are filled with zeroes. When performing a right-shift on a signed value, the value of the sign bit is shifted into the most significant bit (MSB). Let's see what this means with a hypothetical 8-bit signed integer (signed char):

0 1 1 1 1 1 0 0 >> 1 = 0 0 1 1 1 1 1 0

The sign bit (bit 7, which is a 0) is shifted into bit 6. Bit 0 is shifted out. The value started as 124 and ended up as 62.

1 1 0 0 0 0 1 0 >> 1 = 1 1 1 0 0 0 0 1

The sign bit (bit 7, which is a 1) is shifted into bit 6. Bit 0 is shifted out. The value started as -62 and ended up as -31.