## Monday, November 30, 2015

### Display Bits of an Integer

To display bits of an integer you have to check each and every bit so if I have an integer i = 12, it has binary representation 0000 0000 0000 0000 0000 0000 0000 1100.

Lets do it with C++ code. C++ provides bitwise operators for but twiddling, you can simply perform bitwise OR, AND, XOR and other operations like bit shifting using builtin operators.

To check single bit of integer on bit level you need to access each of 32 bits in integer. This is achievable using & operator. & operator has property, the result comes 1 by applying it with two operand bits only if the two bits are 1.

This & is applied to all the bits individually in integer and answer is computed in form of another integer. So if you apply & operation between 2 and 3.

2 = 0000 0000 0000 0000 0000 0000 0000 0010
&&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&&
3 = 0000 0000 0000 0000 0000 0000 0000 0011
-------------------------------------------
2 = 0000 0000 0000 0000 0000 0000 0000 0010

By using same logic, we can create a mask to check if each bit is zero or 1. If mask is set to 1 and later on shifted on left on each bit check some of the mask check for a 4 bit number iterations are like 0001, 0010, 0100, 1000. So after 4 left shift operations and performing & operation on original number, this mask goes zero, which can be used as loop termination condition.

Non-recursive Solution in C++

int number = 12, mask = 1;
cout << 1;
else
cout << 0;
}

But there is an issue with this code, bit pattern will be printed in reverse.

int number = 12, mask = 1;
stack s;
s.push('1');
else

s.push('0');

}

// print elements in stack

This way the bit pattern will be displayed correctly.

There is another efficient way to print in correct order by using an unsigned integer.

For this, consider the following code,

int number = 12;
unsigned int mask = INT_MAX + 1;

cout << 1;
else

cout << 0;

}

Now, INT_MAX gives 2,147,483,647 and by adding 1 to it make it equal to 2,147,483,648 that is equal to 2 ^ 31. That means the 32nd bit of the mask will be ON. Shifting it to the right till it becomes zero and performing & operation prints correct bit pattern of integer.

Note: INT_MAX is present in climit header file.

Recursive Solution in C++

void displayBitwise(int num, int mask = 1) {

cout << ((num & mask) ? 1 : 0);
}

To make this bit pattern more readable, make chunks by separating by space,

void displayBitwise(int num,
int count = 0) {