Bitwise operators in C: 2 Simple Programs to start with

Bitwise operators in C can be very handy in writing simple and efficient codes to solve many logical requirements.
Just to get an overview of how the bitwise operators in C can solve logical problems easily, here we are giving two examples which are tested in Linux environment.

1. Find whether the given input number in even or odd.
2. Find the missing number from the series of natural numbers starting from 1.

Note: To make the code easily understandable, some of the common defensive programming techniques are omitted.
So let’s start with the coding,
.
.
1. Find whether the given input number is even or odd.

Here in this simple program, the input is read from the ‘stdin’ and read into the variable ‘input’. If the entered value is zero, we are jumping to ‘end’ and exits the program.

The code, res = !(input & 1); is computing whether the given number is even or odd. Here the variable ‘res’ will be set to ‘TRUE’ if the variable ‘input’ is containing an even number. Since the last bit of even number will be zero, the ANDing of ‘input’ with 1 will result in zero ((input & 1)), thereby making the entire right hand side operation to ‘TRUE’ (!(input & 1))

2. Find the missing number from the series of natural numbers starting from 1.

In this program we can find the missing number from the given list of natural numbers starting from 1. The input list of numbers is stored in the array variable ‘real_input’. The function ‘GetTheOneMissingNumber()’ will find out the missing number from the given list.

In this program we are performing XOR between all the real numbers starting from 1 to ‘count+1’ and saving it to the local variable ‘xor_res2’. Similarly all the elements in the given list ‘input_list’ are also XOR’ed and saved into the local variable ‘xor_res1’. A final XOR between the values of ‘xor_res2’ and ‘xor_res1’ will give the missing number.

Computation explained,
xor_res1 = X1 ^ X2 ^ X3 ^ X5 ^ X6 ^ X7 ^ X8 ^ X9 ^ X10
xor_res2 = X1 ^ X2 ^ X3 ^ X4 ^ X5 ^ X6 ^ X7 ^ X8 ^ X9 ^ X10
xor_res1 ^ xor_res2 = (X1 ^ X1) ^ (X2 ^ X2) ^ (X3 ^ X3) ^ (X4) ^ (X5 ^ X5) ^… (X10 ^ X10) = X4

3 Comments

    Anonymous

    This is a good one!!
    Finding the missing number using XOR is a cool implementation.
    i think it is possible to solve many logical problems with bitwise operators 🙂 🙂

    Rubio

    In the first example the source code line “res = !(input & 1);” can be re-written as “res = input & 1;” provided,
    res ? printf(“ODD Number\n”) : printf(“EVEN Number\n”);

    Nicole

    Examples are good…
    The finding the missing number using bitwise operators is a new learning to me.
    Expecting more such tips from this site….

Leave a Reply

*
*

Required fields are marked *