Go Down

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

#### jraynes ##### Sep 16, 2010, 06:05 am
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 #1
##### Sep 16, 2010, 06:57 am
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 MSBunsigned 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 bitfor (bit=1, firstParity=0; bit < 8; bit++) {  firstParity ^= (theValue & (1<<bit)) ? 1 : 0;}// Compute parity over next set of 7 bitsfor (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 #2
##### Sep 16, 2010, 09:45 am
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 #3
##### Sep 16, 2010, 01:41 pm
Check here for 5 different ways: http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive

Or:
Code: [Select]
`if ((x & 1) == 0) {  x is even}else {  x is odd}`
More low level bit hacks: www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/

#### westfw #4
##### Sep 16, 2010, 06:12 pm
Code: [Select]
`#include  <util/parity.h>`
Will get you an "optimized" parity_even_bit() function.

#### jraynes #5
##### Sep 17, 2010, 11:07 pmLast 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 #6
##### Sep 18, 2010, 02:25 am
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