Home > Fresh News > count valuable bits in unsigned int

count valuable bits in unsigned int

October 14th, 2009 Leave a comment Go to comments
uint8_t num_of_bits32(uint32_t _arg)
{
    _arg = (_arg & 0x55555555L) + ((_arg >> 1) & 0x55555555L);
    _arg = (_arg & 0x33333333L) + ((_arg >> 2) & 0x33333333L);
    _arg = (_arg + (_arg >> 4)) & 0x0F0F0F0FL;
    _arg = _arg + (_arg >> 8);

    return (uint8_t)(_arg + (_arg >> 16)) & 0x3F;
}

or

int count1(int t)
{
 __asm
 {
        mov edx,t
        mov eax, 0
  cycle : bsf ecx, edx
        jz finish
        inc eax
        inc ecx
        shr edx, cl
        jmp cycle
  finish:
 }
}
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.