This is a discussion on counting the number of bits within the C and C++ Programming forums, part of the Software Development category; Hi, Can anyone tell what is the most efficient way to count the number of bits which are set in ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi, Can anyone tell what is the most efficient way to count the number of bits which are set in a value? Thanks, Prasath.K Last edited by Booom : 08-18-2007 at 01:24 AM. |
| Sponsored Links |
| |||
| hey, foo(unsigned char *ByteField) { int i=0,j=0; unsigned char *BytePos; short Bit; BytePos = ByteField + sizeof(ByteField); for (i=0; i { if (*(BytePos - i) > (char ) 0) { for (j=0; j<8; j++) { if (((*(BytePos - i)) & 1<< { Bit = (i * 8) + j; printf("Bit Set %d n",Bit); } } } } } Should give u the bit which are set
__________________ Venkat knowledge is Power |
| |||
| try the followin function, i dint try it yet, but hope it will work int countBits(int val){ int count=0; while(val != 0){ if((val>>1) == 1){ count++; } val >>= 1; } return count; }
__________________ SeeSamJagan- Sky is not the "LIMIT", Death is not the END, There is still something beyond.... |
| |||
| Hi, i just made small mistake in the last posttry the modified function int countBits(int val){ int count=0;}
__________________ SeeSamJagan- Sky is not the "LIMIT", Death is not the END, There is still something beyond.... |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| how to create random number in c? | Murali | C and C++ Programming | 6 | 07-23-2008 12:26 AM |
| Bits and bytes | srikumar_l | Computer Hardware | 0 | 12-23-2007 03:07 AM |
| Counting Rec of multiple tables in one query? | oxygen | Database Support | 6 | 12-06-2007 07:40 AM |
| To get random number in mysql | Murali | Database Support | 7 | 11-05-2007 11:34 PM |
| Hiding first number of characters. | S.Vinothkumar | Database Support | 4 | 09-28-2007 07:37 AM |