Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coun the number of bits set in a variable #2

Open
BumerSan opened this issue Aug 8, 2023 · 1 comment
Open

Coun the number of bits set in a variable #2

BumerSan opened this issue Aug 8, 2023 · 1 comment

Comments

@BumerSan
Copy link

BumerSan commented Aug 8, 2023

I'm not a real programmer, but I can use your unit perfectly in my private projects.
If possible I would like a Function BitCount128(b: 128): integer;
Thanks for your great work.

@laoqiuqiu
Copy link

const
  M1: UInt64 = $5555555555555555;
  M2: UInt64 = $3333333333333333;
  M3: UInt64 = $0F0F0F0F0F0F0F0F;
  M4: UInt64 = $00FF00FF00FF00FF;
  M5: UInt64 = $0000FFFF0000FFFF;
  M6: UInt64 = $00000000FFFFFFFF;

Function BitCount64(V: UInt64): Integer; register;
begin
  V := (V and M1) + ((V shr 1) and M1);
  V := (V and M2) + ((V shr 2) and M2);
  V := (V and M3) + ((V shr 4) and M3);
  V := (V and M4) + ((V shr 8) and M4);
  V := (V and M5) + ((V shr 16) and M5);
  V := (V and M6) + ((V shr 32) and M6);
  Result := Integer(V);
end;

Function BitCount128(V: UInt128): Integer; register;
begin
  Result := BitCount64(V.dc0);      // c0 is low 64 bits
  if V.dc1 <> 0 then
    Inc(Result, BitCount64(V.dc1))  // c1 is high 64 bits
end;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants