package com.mindprod.example;
import java.io.UnsupportedEncodingException;
import static java.lang.System.*;
/**
* Detect if a byte has even or odd parity, i.e. even or odd number of 1 bits.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.1 2009-08-03 add Eric Sosman's xor method
* @since 2009-07-29
*/
public final class TestParity
{
/**
* Calculate parity of a single byte
*
* @param b byte to test
*
* @return true of if odd parity, false if even parity
*/
private static boolean isOddParity( final byte b )
{
int bb = b;
int bitCount = 0;
for ( int i = 0; i < 8; i++, bb >>>= 1 )
{
if ( ( bb & 1 ) != 0 )
{
bitCount++;
}
}
return ( bitCount & 1 ) != 0;
}
/**
* Calculate parity of a single byte, using Eric Sosman's xor method
*
* @param b byte to test
*
* @return true of if odd parity, false if even parity
*/
private static boolean isOddParityViaSosman( final byte b )
{
final int bb = b & 0xff;
int parity = bb ^ ( bb >> 4 );
parity ^= parity >> 2;
parity ^= parity >> 1;
return ( parity & 1 ) != 0;
}
/**
* Test harness
*
* @param args not used
*
* @throws java.io.UnsupportedEncodingException in case UTF-8 support missing.
*/
public static void main( String[] args ) throws UnsupportedEncodingException
{
out.println( isOddParity( ( byte ) 0xff ) );
out.println( isOddParity( ( byte ) 0x70 ) );
out.println( isOddParityViaSosman( ( byte ) 0xff ) );
out.println( isOddParityViaSosman( ( byte ) 0x70 ) );
}
}