The Magic of Bitwise Operators

Harsh Joshi
2 min readFeb 26, 2020

Bitwise Operators are one of my favourite tools in programming. They seem overwhelming at first but once one becomes acquainted, it’s a piece of cake. Bitwise operators are intriguing because of their practical implementation. These work on the mathematics of logic and fundamental operations involving bits (which are used in Machine Instructions).

Bitwise operators directly deal with the binary of a number. Bitwise operators are interesting to study because they have a logic which is similar to none. This is the reason many don’t quite understand the working at the start. It is very important to know before starting to study Bitwise Operators that these operate on binary and binary is not the same as a decimal. The concept of the binary of a number in itself is a standalone subject to study and brings along different dimensions and has different representation.

Let’s Talk Bitwise Now

In programming, there is a concept of “signed” and “unsigned” integers. These representations denote positive and negative numbers. This concept is not generic to all the programming languages but is explicit to some.

Java, for instance, does not support “unsigned” integers whereas C++ has support for both “signed” and “unsigned” numbers. Signed numbers are represented using 2’s Complement.

2’s Complement While Writing Code to a Problem:

While it is very easy to take 2’s complement mathematically. It becomes very intriguing when it has to be done programmatically.

Mathematically, Given a binary number, we flip the bits and add 1 to obtain the 2’s complement of a number. But to do this programmatically, first of all, we won’t be given the binary number, rather the decimal equivalent of it and we will not be asked to find 2’s complement rather use this concept to derive some other result.

Let us understand with an example:

The binary representation of 2 is 10.

To obtain the 2’s complement of 010 we flip the bits to make it 101 and add 1 to make it 110 which is 6 in decimal. So the 2’s complement of 2 is 6 (In 3-bit Representation)

It is very important to note that, the bit representation i.e. the total number of bits used to represent the number plays a huge role in determining these calculations. In the examples above we calculated the 2’s complement assuming a 3-bit representation i.e. a number can be represented using 3 bits.

To do it programmatically,

The 2's complement of input x in k-bit representation is 2^k-x.

For example, 2’s complement of 2 is 2³-2= 6 which is 101 in binary.

TO BE CONTINUED…

--

--