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.

New implementation...
< >
tkoenig