This is the first artical on Bitwise Operation, and today I will discuss how to multiple numbers using bitwise operation.
Before we dwell in the multiplication lets do some quick overview of bitwise left shift operations. Left shift operator is represented by ‘<<’.
Whenever we left shift a number by 1 we move each bit present at position x to position x+1, and append 0 at the position zero (Also, known as LSB.)
Left shift example:
E.g.:
Left shift 13 by 1. 13 is represented as 1101 13 << 1 = 11010
Similarly we want to left shift something by 5 digits, each bit is moved 5 positions to left and last 5 LSB bits are replaced with zero.
13 << 5= 110100000For multiplication we only need to know about left shift so lets get started.
Example 1: Multiple 13 and 2 To multiply any number represented in binary we need to left shift the number by 1. So, if we want to multiply 13 by 2 we just need to perform 1 operation.
i.e. 13 << 1
The above operation produces: 11010, which is equivalent to 26 ( 13*2 = 26 )in decimal.
Example 2: Calculate 170* 2 Binary of 170 is 10101010 Left shift 10101010 < 1 = 101010100 ( 340 in decimal )Conclusion: Left shift a number by 1 to multiply a number by 2.
The above method can be extended multiply a number by 4,8,16,32 and so on… So, if you want to multiple a number ‘x’ by 4, multiply the number x with 2, 2 times.
I.e.:
x<<1 // to get x*2 and again x<<1 //to get x*2*2 /* The above expression is equivalent to x<<2. */
In general, if we want to multiple a number ‘x’ with another number which can be represented as 2^n, we can get the result by doing x<<n. ( Left shit x by n ) Multiplying x with y, where x > 1 and y > 1 In binary each bit can take 2 values 0 or 1 and each bit correspond to value which can be determined as follows: If the bit at position n is set, it means that that set bit add 2^n to the total value of the number.
E.g.:
= 1 0 0 1 0 0 0 1 = 2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0 = 128 0 0 16 0 0 0 1 = 128 + 16 + 1 = 145
So if we want to multiple any number ‘x’ with 145, how do we calculate the result using bitwise operation.
To demonstrate the working we will multiply 11 with 145 (Result should be 1595.)
In the binary representation of 145, bits at position 7, 4, 0 (0 based positioning. )
Calculation:
= 11 * 145 = 11 * (2^7 + 2^4 + 2^0) = 1011 * (2^7 + 2^4 + 2^0) // 11 in binary is 1011 = 1011 * 2^7 + 1011 * 2^4 + 1011 * 2^0 = 1011 <<7 + 1011 << 4 + 1011 << 0 = 10110000000 + 10110000 + 1011 = 11000111011 // 1595 in binary = 1595So to get the result we need to represent the number in terms of power of two. And then use the bitwise operation and addition to get the result of a complicated multiplication.