Saturday, September 26, 2009

Even Parity -- comparison of two algorithms

To set a ASCII character to even parity, we first count the number of bits with the value of 1. If the number is even, the ASCII character is already of even parity. Otherwise, we set the most significant bit of the ASCII character to 1 to make it even parity. The follow code (in Java) demonstrates that:

public static byte setEvenParity(byte b)
short countOne = 0;

if (0 != (b & 0x01)) ++countOne;
if (0 != (b & 0x02)) ++countOne;
if (0 != (b & 0x04)) ++countOne;
if (0 != (b & 0x08)) ++countOne;
if (0 != (b & 0x10)) ++countOne;
if (0 != (b & 0x20)) ++countOne;
if (0 != (b & 0x40)) ++countOne;

byte evenB = (1 == (countOne % 2)) ? (byte)(b | 0x80) : b;

return evenB;

Can we do a little improvement to it?

As we can see, when we convert the same byte twice, the same processes of checking and setting the most significant bit are repeated. What if we remember what we have done in the first time and apply the result to the second time. For example, the first time we see character 'T' whose binary form is "0101 0100", we check and find out that it has 3 bits with the value of 1. We then set its most significant bit as 1 to make it as "1101 0100". When we see 'T' again, we should know immediately that the output should be "1101 0100" without doing the checking again.

Or even better, if we already know who need setting even parity bit and who need not before we process any string. After all, there are only 128 ASCII characters. So all we need is a preset table. When we see character 'T', we check the table and get "1101 0111".

private static int[] withEvenParity = {

public static byte fasterSetEvenParity(byte b)
int i = b & 0x7f;

byte evenB = (byte)withEvenParity[i];

return evenB;

Note: we can use the first algorithm to generate the withEvenParity[] array.

Is the second algorithm really faster? I ran a little test with this program and the result below.

public static void main(String arg[])
String s = "This is a test string.";

byte[] bytes = s.getBytes();

for (int i = 0; i < 100000000; ++i)
for (int j = 0; j < bytes.length; ++j)
byte result =

if (0 == i)
System.out.print(Integer.toHexString(bytes[j] & 0xff)
+ ":" + Integer.toHexString(result & 0xff) + " ");


Using the first algorithm, the running time of the program is:

real 0m23.156s
user 0m22.863s
sys 0m0.015s

Using the second algorithm, the running time of the program is:

real 0m6.838s
user 0m6.692s
sys 0m0.026s

Yeah! The faster one is really faster.

Read my other post of Print byte in hex with the similar idea to speed things up.

No comments:

Post a Comment