Logo

Programming-Idioms

  • Perl
  • Ada
  • Js

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.

let i = 42
i.toString(2)
  .split('')
  .reduce((parity, bit) => parity ^ bit, 0)
$p = ($count = @ones = (sprintf '%b', $i) =~ /1/g) % 2;

sprintf %b converts the integer $i into a string of zeros and ones. This is matched against a '1' repeatedly (courtesy of the g regex modifier). The result of that is a list of matches returned into list variable @ones.

The list variable @ones is then assigned to scalar $count, which yields a count of the list items.

Modulo 2 of the count is then taken in order to get the parity. If the number of bits is odd, then there will be a one remainder, and one is taken as true by Perl
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