-
Count Number of Bits in the Given Number
Find the number of bits in a Number is one of the most commonly asked interview questions which has many different types of correct Solutions
The most efficient,simple and general one is the following :
[P]
int bitcount (unsigned int n)
{
int count=0 ;
while (n)
{
count++ ;
n &= (n - 1) ;
}
return count ;
}
[/P]
-
Obvious Inefficient Solution for Bit Count
[P]
int bitcount (unsigned int n)
{
int count=0;
while (n)
{
count += n & 0x1u ;
n >>= 1 ;
}
return count ;
}
[/P]
-
Most Common and Hard Microsoft Byte based Question
First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always 0. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is 1. Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).
-
Convert lowercase characters into Uppercase using Bitwise Operators
-
How to Reverse bits of an unsigned integer.
[P] #define reverse(x)
(x=x>>16|(0x0000ffff&x)<<16,
x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8,
x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4,
x=(0xcccccccc&x)>>2|(0x33333333&x)<<2,
x=(0xaaaaaaaa&x)>>1|(0x55555555&x)<<1)[/P]
-
How do we test whether a number is a power of two?
The number n is a power of 2 if and only if n&(n-1) is zero
-
Fast Bit Counting Routines
(http://infolab.stanford.edu/~manku/bitcount/bitcou)
A good description on how to count the number of bits in an integer.Lots of code snippets and examples are given