[fpc-pascal] Bitcounting
Jesus Reyes A.
jesusrmx at gmail.com
Sat Mar 5 19:15:35 CET 2016
En Sat, 05 Mar 2016 12:03:24 -0600, Bart <bartjunk64 at gmail.com> escribió:
> Hi,
>
> Does FreePascal have a routine for counting bits?
> So that e.g. BitCount(%1001100100001) gives 5 (number of bits that are
> 1)?
>
> I came up with (extracted from IntToBin()):
>
> function BitCount(N: Int64): Integer;
> var
> Q: QWord;
> i: Integer;
> begin
> Result := 0;
> Q := QWord(N);
> for i := 0 to (8 * SizeOf(N) - 1) do
> begin
> if ((Q and 1) = 1) then Inc(Result);
> Q := Q shr 1;
> end;
> end;
>
> Surely this can be done better?
>
> Bart
function BitCount(N: Int64): Integer;
var
i: Integer;
begin
Result := 0;
if N=0 then
exit;
for i := 0 to (8 * SizeOf(N) - 1) do
begin
if (N and (1 shl i)) <> 0 then Inc(result);
end;
end;
not tested :D
Jesus Reyes A.
More information about the fpc-pascal
mailing list