To understand the bitwise operators in C,
we will study here some examples. When we want to simulate on paper
operators &
, |
^
and ~
, we have to proceed in three steps
steps:
Consider the following example with the AND operator:
unsigned char a=197, b=227 , s;
s = a & b;
Step 1: convert a
and b
to binary (an online converter is available here ).
$$ a = (197)_{10} = (1100\:0101)_2 $$ $$ b = (227)_{10} = (1110\:0011)_2 $$
Note that we convert to 8 bits, because the unsigned char
is encoded on 8 bits. If it were an int
you would have to convert to 32 bits.
Step 2: Perform the AND operator on each bit:
$$ \begin{array}[t]{r} 1100\:0101 \\ \& \; 1110\:0011 \\ \hline 1100\: 0001 \end{array} $$
Step 3: Convert the result s
from binary to decimal:
$$ s = (1100\:0001)_2 = (193)_{10} $$
Let's check the result:
Let's consider the same example with theXOR operator:
unsigned char a=197, b=227 , s;
s = a ^ b;
Step 1: same binary conversion as on the previous example:
$$ a = (197)_{10} = (1100\:0101)_2 $$ $$ b = (227)_{10} = (1110\:0011)_2 $$
Step 2: perform the XOR on each bit:
$$ \begin{array}[t]{r} 1100\:0101 \\ \bigoplus \; 1110\:0011 \\ \hline 0010\: 0110 \end{array} $$
Step 3: Convert the result s
from binary to decimal:
$$ s = (0010\:0110)_2 = (38)_{10} $$
Let's check the result:
Consider the example below which inverts the variable a
bit by bit:
unsigned char a=225, s;
s = ~a;
Step 1: convert a
to binary:
$$ a = (225)_{10} = (1110\:0001)_2 $$
Step 2: apply the NOT operator on each bit:
$$ \begin{array}[t]{r} a &=& \; 1110\:0001 \\ \hline s = \overline{a} &=& 0001\: 1110 \end{array} $$
Step 3: Convert the result s
from binary to decimal:
$$ s = (0001\:1110)_2 = (30)_{10} $$
Let's check the result:
Complete the following program so that it calculates the NAND bit by bit
of the variables a
and b
:
#include <stdio.h>
int main(void) {
unsigned char a =125, b=89, s;
// a NAND b => s
// COMPLETE HERE
// Display the result
printf ("s = %d\n", s);
return 0;
}
To complete the quiz, you will need a paper and pencil to reproduce the steps presented in the examples in this course. You can also use this online binary/decimal converter.
What does the following program display?
unsigned char a=3, b=5;
printf ("%d", a & b );
What does the following program display?
unsigned char a=3, b=5;
printf ("%d", a | b );
What does the following program display?
unsigned char a=3, b=5;
printf ("%d", a ^ b );
What does the following program display?
unsigned char a=0xAA, s;
s = ~a;
printf ("%u", s );
What does the following program display?
unsigned char a=3, b=5, s;
s = a ^ ~b;
printf ("%u", s );