Hello Folks!
I'm new in asm programming. I want to enumerate the set bits from a given buffer. I wrote first the function in C and then I tried to translate it to inline assembly. the results are diferent but I can't see what I did wrong:





int BitSetCounter( char* buffer, int size )
{
int RetVal = 0;

for ( int i = 0; i < size; i++ )
{
for ( int j = 0; j < 8; j++ )
{
if ( ( buffer[i] >> j ) & 1 )
{
RetVal ++;
}
}
}

return RetVal;

}


int _BitSetCounter( char* buffer, int size )
{
int RetVal = 0;
int* _size = (int *)size;

__asm
{
pushad
xor esi, esi
mov edi, buffer

ReadByte:
mov al, byte ptr ds:[esi+edi]
xor edx, edx
mov bl, al

VerifyBit:
mov cl, dl
shr bl, cl
and bl, 1
jz _continue

inc RetVal

_continue:
inc edx

cmp edx, 8
jl VerifyBit

inc esi
cmp esi, _size
je end

jmp ReadByte

jmp end
end:
popad
}


return RetVal;
}

int main( int argc, char* argv[] )
{
printf( "Result of the function in C : %i\n", BitSetCounter( "A", sizeof( "A" ) ) );
printf( "Result of the function in Asm: %i\n", _BitSetCounter( "A", sizeof( "A" ) ) );
return 1;
}


The result must be two as in binary 65 is equals to 1000001 but the asm function is returning 1....

What's wrong?

My best regards
Cthulhu
Posted on 2004-09-11 18:02:02 by Cthulhu
You aren't resetting BL to AL on further iterations.
This is a much better way:


int _BitSetCounter( char* buffer, int size )
{
__asm {
push esi
push edi
mov esi,buffer
mov ecx,size
xor edx,edx
jecxz nobytes
ReadByte:
push 8
pop edi
lodsb
VerifyBit:
shr al,1
adc edx,0
dec edi
jnz VerifyBit
loop ReadByte
nobytes:
pop edi
pop esi
xchg edx,eax
}
}
Posted on 2004-09-11 18:41:59 by Sephiroth3
What a dumb mistake :oops:
Thank you very much Sephiroth3
Posted on 2004-09-11 19:30:24 by Cthulhu