You approach is inefficient and more complex than it has to be. I'll just give you the right idea:
You need to test all bits in the integer value and write 0 is the bit is set, 1 is the bit is not set. How to do it? First create an integer with N-th bit set. Let's call this number a "mask" (this is what it is, its purpose). This is done by the left shift of 1 using the shift operator '<<': If the bit's number is
N
, the mask is
1 << N
.
After that, calculate binary AND of the integer value you test and the mask, using the bitwise '&' operator. If the bit
N
is clear, the result or AND operation is zero, non-zero otherwise.
This is all you need.
See also:
http://www.learncpp.com/cpp-tutorial/38-bitwise-operators[
^].
[EDIT]
Also, there is no a need to check up for negative integer. You can represent negative integers in exact same way as positive; the algorithm is totally agnostic to the sign. By the way, the integers are usually represented using
two's complement representation, which makes the arithmetic operations agnostic to the sign. This is an interesting and important matter, must-know for all software developers:
http://en.wikipedia.org/wiki/Two%27s_complement[
^].
—SA