Go Down

Topic: Calculating parity of a binary number (Read 7185 times) previous topic - next topic

jraynes

Hi,

I have an external device which sends binary data to my Arduino 16 bits at a time.  Of these 16 bits, the first bit is even parity of next 7 bits while the last bit is odd parity for the previous 7 bits. I have an idea of how to do this in my head with a loop and a few conditionals but I don't quite understand how I would do this in Wiring. Can someone help me?

Thanks in advance :)

RuggedCircuits

By "do this" I assume you mean check the parity?

Here's a potential starting point:

Code: [Select]
unsigned theValue; // 16-bit value from external device

// I'm assuming the "first bit" is the LSB and the "last bit" is the MSB
unsigned evenParity = (theValue & (1<<0)) ? 1 : 0;
unsigned oddParity = (theValue & (1<<15)) ? 1 : 0;
unsigned firstParity, secondParity, bit;

// Compute parity over first set of 7 bits past even parity bit
for (bit=1, firstParity=0; bit < 8; bit++) {
 firstParity ^= (theValue & (1<<bit)) ? 1 : 0;
}

// Compute parity over next set of 7 bits
for (bit=8, secondParity=0; bit < 15; bit++) {
 secondParity ^= (theValue & (1<<bit)) ? 1 : 0;
}

// Now do comparisons of firstParity vs. evenParity and secondParity vs. oddParity


Efficiencies can be realized in the above but hopefully this is more clear than efficient  ;)

--
The Gadget Shield: accelerometer, RGB LED, IR transmit/receive, light sensor, potentiometers, pushbuttons

squiggler

here is an efficient parity routine :-
Code: [Select]
unsigned char parity(unsigned long ino)
{
unsigned char noofones = 0;

while(ino != 0)
{
noofones++;
ino &= (ino-1); // the loop will execute once for each bit of ino set
}

/* if noofones is odd, least significant bit will be 1 */

return (noofones & 1);
}


anio


westfw

Code: [Select]
#include  <util/parity.h>
Will get you an "optimized" parity_even_bit() function.

jraynes

#5
Sep 17, 2010, 11:07 pm Last Edit: Sep 17, 2010, 11:08 pm by jraynes Reason: 1
That would be great but I can't seem to get that to work. I tried running 1111111 through parity_even_bit which should return true for even parity but it always returns false. Any ideas?

westfw

It says "returns 1 if val has an odd number of bits set."
Ie it returns a bit that you'd add to your transmission to make the whole thing be even parity...

Go Up