Explain the methodologies of various type that can be used to manipulate bits in register. Elaborate with proper examples.
2. Counting the number of ones in the binary representation of the given number.
The basic approach to evaluate the binary form of a number is to traverse on it and count the number of ones. But this approach takes log2N of time in every case.
Why log2N ?
As to get a number in its binary form, we have to divide it by 2, until it gets 0, which will take log2N of time.
3. Checking if the ith bit is set in the binary form of the given number.
To check if the ith bit is set or not (1 or not), we can use AND operator. For instance, assuming that we have a number N, and to check whether it’s ith bit is set or not, we can AND it with the number 2i . The binary form of 2i contains only ith bit as set (or 1), else every bit is 0 there. When we will AND it with N, and if the ith bit of N is set, then it will return a non zero number (2i to be specific), else 0 will be returned.