Logo

Programming-Idioms

  • D
  • Ruby

Idiom #265 Even parity bit

Calculate the parity p of the integer variable i : 0 if it contains an even number of bits set, 1 if it contains an odd number of bits set.

function Parity(n: Int32): Integer;
begin
  Result := Ord(Odd(PopCnt(DWORD(n))));
end;

var
  i: Int32;
begin
  i := 42;
  writeln('Parity(42) = ',Parity(i));
end.

PopCnt returns the number of set bits, it only accepts unsigned parameters, hence the typecast to DWORD (also 32-bit).
function Parity(n: Integer): Integer;
var
  Mask, I, Bits: Integer;
begin
  Bits := 0;
  for I := 0 to SizeOf(Integer)*8 - 1 do
  begin
    Mask := 1 shl I;
    if ((n and Mask) <> 0) then Inc(Bits);
  end;
  Result := Ord(Odd(Bits));
end;

begin
  writeln(Parity(42));
end.

Ord(False) equals 0
p = i.digits(2).count(1)[0]
parity(Number) -> parity(Number, 0).

parity(Number, Count) when Number band 1 == 1 ->
        parity(Number bsr 1, Count + 1);
parity(Number, Count) when Number > 0 ->
        parity(Number bsr 1, Count);
parity(_, Count) ->
        Count rem 2.

New implementation...
< >
tkoenig