/*
 * [TestParity.java]
 *
 * Summary: Detect if a byte has even or odd parity, i.e. even or odd number of 1 bits.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2009-07-29 initial version
 *  1.1 2009-08-03 add Eric Sosman's xor method
 */
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;
        // Process bits right to left, shifting each bit in turn into the lsb position.
        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 ) );   // false
        out.println( isOddParity( ( byte ) 0x70 ) );   // true
        out.println( isOddParityViaSosman( ( byte ) 0xff ) );   // false
        out.println( isOddParityViaSosman( ( byte ) 0x70 ) );   // true
        }
    }