Cristi Lupu - 1 year ago 110
C Question

# Counting the binary representation of an Integer

I have to count the length of binary representation of an integer.
I've tried something like this:

``````int binaryLength(int n)
{
int i = 32;
while (i > 0)
{
if (n >> i & 1) break;
else i--;
}
return i;
}
``````

But when i have number like 9 (1001), this function returns me 32.

I'd abandon the loop approach if I were you.

Here's the fastest way I know of - coded specifically for a 32 bit `int`. It will not work for a negative integer (the bit patterns for negative integers are platform dependent anyway). Add an extra line for a 64 bit `int`; the scheme ought to be obvious.

``````int binaryLength(int n)
{
int i = 0; // the minimum number of bits required.
if (n >= 0x7FFF) {n >>= 16; i += 16;}
if (n >= 0x7F) {n >>= 8; i += 8;}
if (n >= 0x7) {n >>= 4; i += 4;}
if (n >= 0x3) {n >>= 2; i += 2;}
if (n >= 0x1) {n >>= 1; i += 1;}
return i;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download