Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.

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.
print *,poppar(i)
let i = 42
i.toString(2)
  .split('')
  .reduce((parity, bit) => parity ^ bit, 0)
int p = Integer.bitCount(i) % 2;
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.
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.
$p = ($count = @ones = (sprintf '%b', $i) =~ /1/g) % 2;
p = bin(i).count('1') % 2
p = i.digits(2).count(1)[0]
let p = i.count_ones() % 2;
(define (popcount x)
  (let loop ([s x]
             [count 0])
    (cond [(zero? s) count]
          [(odd? s) (loop (arithmetic-shift s -1) (add1 count))]
          [else (loop (arithmetic-shift s -1) count)])))

(define i 42)
(popcount i)

New implementation...
< >
tkoenig