News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

64 bit population count

Started by donkey, October 13, 2011, 03:46:06 AM

Previous topic - Next topic

donkey

I needed to count the number of set bits in a 64 bit number in x86-64 mode and adapted the popcount function to handle 64 bits:

popcount64 FRAME Value
;mov rcx,[Value] // this is implied by fastcalll

mov r9,0x5555555555555555
mov r10,0x3333333333333333
mov r11,0x0F0F0F0F0F0F0F0F

mov rax,rcx
shr rax,1
and rax,r9
sub rcx,rax
mov rax,rcx
shr rax,2
and rcx,r10
and rax,r10
add rcx,rax
mov rax,rcx
shr rax,4
add rax,rcx
and rax,r11

mov rcx,rax
shr rcx,8
add rax,rcx
mov rcx,rax
shr rcx,16
add rax,rcx
mov rcx,rax
shr rcx,32
add rax,rcx

and rax,0x7F

RET
ENDF
"Ahhh, what an awful dream. Ones and zeroes everywhere...[shudder] and I thought I saw a two." -- Bender
"It was just a dream, Bender. There's no such thing as two". -- Fry
-- Futurama

Donkey's Stable

drizz

Algo from "Hacker's Delight" book:
option prologue:none, epilogue:none
.code
BitCount proc Value
mov rax,rcx
mov rdx,rcx
mov rcx,07777777777777777h
mov r8,00F0F0F0F0F0F0F0Fh
mov r9,00101010101010101h
shr rdx,1
and rdx,rcx
sub rax,rdx
shr rdx,1
and rdx,rcx
sub rax,rdx
shr rdx,1
and rdx,rcx
sub rax,rdx
mov rdx,rax
shr rdx,4
add rax,rdx
and rax,r8
imul rax,r9
shr rax,64-8
ret
BitCount endp
end
The truth cannot be learned ... it can only be recognized.