To compute the parity of a byte, you can do
byte data = ...;
int parity = data ^ (data >> 4);
parity ^= parity >> 2;
parity ^= parity >> 1;
parity &= 1;
as an SSCCE
/*
* @(#)TestParity.java
*
* Summary: Detect if a byte has even or odd parity, i.e. even or odd
number of 1 bits.
*
* Copyright: (c) 2009 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.6+
*
* Created with: IntelliJ IDEA IDE.
*
* 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.out;
/**
* 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
{
// -------------------------- PUBLIC STATIC METHODS
--------------------------
/**
* Calculate parity of a single byte
*
* @param b byte to test
*
* @return true of if odd parity, false if even parity
*/
public 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
*/
public 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;
}
// --------------------------- main() method
---------------------------
/**
* 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
}
}
--
Roedy Green Canadian Mind Products
http://mindprod.com
"Patriotism is fierce as a fever, pitiless as the grave, blind as a stone, and as irrational as a headless hen."
~ Ambrose Bierce (born: 1842-06-24 died: 1914 at age: 71)