[fpc-pascal] Bitcounting
Philippe Lévi
Philippe at quarta.com.br
Sat Mar 5 19:09:52 CET 2016
sorry ... need change intToStr in my suggestion by something like intToStrBin
length( strChange( intToStrBin( N, '0', ''));
but it is just for fun!
________________________________________
De: fpc-pascal-bounces at lists.freepascal.org <fpc-pascal-bounces at lists.freepascal.org> em nome de Bart <bartjunk64 at gmail.com>
Enviado: sábado, 5 de março de 2016 15:03
Para: FPC-Pascal users discussions
Assunto: [fpc-pascal] Bitcounting
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
_______________________________________________
fpc-pascal maillist - fpc-pascal at lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
More information about the fpc-pascal
mailing list