Count maximum contiguous set bits in an integer .



Hi All

I have written a program to count the maximum contiguous set bits in an
integer .
Like if my binary representation of integer is :
1100111 : then output should be 3.
111000111110000101010111111 : then output should be 6.

I am including the snippet below.
How can I optimize this code and also is there a one liner to
implement the same.
(Like for power of 2 we have got (number & (number -1))).

Here is the program:

int main()
{
int count=0,n,i,temp=0;
printf("Enter the number \n");

/*Numer is in decimal for calculation we have to use binary
representation for calculation*/

scanf("%d",&n);

for (i=0;i<(8*sizeof(int));i++)
{
if((n&1)==1)
count++;
else
{
if (temp<count)
temp=count;
count=0;
}
n= n>>1;
}
if (temp==0)
printf("count of contiguous bits= %d\n",count);
else
printf("count of contiguous bits = %d\n",temp);

return 0;
}

.



Relevant Pages

  • Re: Bit shifts and endianness
    ... in 'int x' have binary representation in memory. ... 052 or 0x2A the int in memory looks something like 0..00101010 ... "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. ...
    (comp.lang.c)
  • Re: Bit shifts and endianness
    ... games with language. ... Values in C stored in 'int x' have binary representation in memory. ...
    (comp.lang.c)
  • Re: Question from a Newb
    ... >int main ... algorithm he is using (an old 'English' mechanism derived from ... start infinite loop (i.e. termination will be internal) ... the binary representation. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: c program binary/image in memory
    ... > int a = 488776; ... > This implies that somewhere in the executable, ... > 488776 is stored in the binary representation specific ...
    (comp.lang.c)
  • Re: Writing a float or doubles byte values
    ... > I would like to print (cout) the binary representation of a double. ... The program that is copied below prints an int variable ... // This program works only with 32-bit int variables. ...
    (comp.lang.cpp)