[NO-PARSE]// main.cpp
#include <iostream>
#include <climits>
static const bool parity_table[256] =
{
#define P2(n) n, n^1, n^1, n
#define P4(n) P2(n), P2(n^1), P2(n^1), P2(n)
#define P6(n) P4(n), P4(n^1), P4(n^1), P4(n)
P6(0), P6(1), P6(1), P6(0)
};
template <typename T>
class ParityEvaluate
{
public:
ParityEvaluate(const T n) : val(n) {}
operator bool ()
{
T r = val;
switch (sizeof(T)*CHAR_BIT)
{
case 8: // 8 bit
r = parity_table[r];
break;
case 16: // 16 bit
r ^= r >> 8;
r ^= r >> 4;
r = parity_table[r & 0xF];
break;
case 32: // 32 bit
r ^= r >> 16;
r ^= r >> 8;
r = parity_table[r & 0xFF];
break;
case 64: // 64 bit
r ^= r >> 24;
r ^= r >> 16;
r = parity_table[r & 0xFFFF];
break;
}
return r;
}
private:
T val;
};
int main()
{
/*
** Ex:
** 8 bit: 7 = 00000111
** 8 bit: 20 = 00010100
**
** Parity calculation is based off of # of set 1 bits
** in the binary representation of a value
*/
unsigned char n = 117;
std::cout << "Number: " << static_cast<unsigned>(n) << std::endl;
ParityEvaluate<unsigned char> odd_parity(n);
std::cout << "Parity: " << (odd_parity ? "Odd" : "Even") << std::endl;
std::endl(std::cout);
return 0;
}[/NO-PARSE]