How to compare Odd and Even number on binary and decimal?
rmanze
Posts: 2
HEllo,
I'm new here, I want to know how can i compare between Odd and Even number with both binary and decimal?
let say the binary input comes from Pin-0 to pin-4 and how can i convert this input into decimal and then compare between Odd and Even? pls help me
Thanks
I'm new here, I want to know how can i compare between Odd and Even number with both binary and decimal?
let say the binary input comes from Pin-0 to pin-4 and how can i convert this input into decimal and then compare between Odd and Even? pls help me
Thanks
Comments
This would be done in assembly language or C.
Some languages might have an "ISODD" or "ISEVEN" function.
To find examples, google "parity check C" or google "isodd".
Following is a parity check function in C, but this is checking ALL the bits. You would just need to check the least significant bit...
i.e.
00000000 = even
00000001 = odd
// ParityCheck Function
unsigned char ParityCheck(unsigned char EightBitChar)
{
unsigned int Tmp;
// Shift left 4 bits to right nibble of byte (0's will fill left nibble), store to Tmp.
Tmp = (EightBitChar >> 4);
// XOR left and right nibbles of EightBitChar - Any 1's will cancel theselves out.
EightBitChar = (EightBitChar ^ Tmp);
// Shift left 2 bits of right nibble to far right of byte (0's will fill left 2 bits), store to Tmp.
Tmp = (EightBitChar >> 2);
// XOR right two bits of EightBitChar and Tmp - Any 1's will cancel theselves out.
EightBitChar = (EightBitChar ^ Tmp);
// Shift 2nd bit to far right of byte (0 will fill far left bit), store to Tmp.
Tmp = (EightBitChar >> 1);
// XOR right bit of EightBitChar and Tmp - Any 1's will cancel theselves out.
EightBitChar = (EightBitChar ^ Tmp);
// AND with mask to remove all 1's except far right bit (leave that bit a 1 or 0).
EightBitChar = (EightBitChar & 0b00000001);
// Return remaining bit which should be odd 1 or even 0.
return EightBitChar;
}
Thanks for your reply i think this might help me, anyway your explaination will be my reference..
thanks a lot.
If you AND your variable with 1 the result will be zero if the number is even, it will be one if it is odd.
As you numbers are coming from pins P0 to P4 just read them from INA. P0 will have to be the least significant bit for the test above to work.
-Phil
Genius! Why didn't I think of that?? I had this problem the other day and your solution is far more elegant than mine.