#include <iostream>
#include <bitset>

using namespace std;

/*
    This function converts
    an unsigned binary number
    to reflected binary Gray code.
*/
unsigned int Binary2Gray(unsigned char in_number){
    return in_number ^ (in_number >> 1); // The operator >> is shift right. The operator ^ is exclusive or.
}

/*
    This function converts
    a reflected binary Gray code number
    to a binary number.
*/
unsigned int Gray2Binary(unsigned char in_number){
    unsigned short mask = in_number;
    while (mask) {
        mask >>= 1;
        in_number ^= mask;
    }
    return in_number;
}

int main(){
    //4-bit binary number into 4-bit Gray code:
    cout << "Decimal -> Binary -> Gray:" << endl;
    for(int i=0; i<16; i++){
        cout << "[" << i << "]" << " -> "
            << bitset<4>{i} << " -> "
            << bitset<4>{Binary2Gray(i)}
            << endl;
    }

    cout << "Gray -> Binary -> Decimal:" << endl;
    //4-bit Gray code into 4-bit binary number:
    for(int i=0; i<16; i++){
        cout << "[" << bitset<4>{Binary2Gray(i)}
            << "]" << " -> "
            << bitset<4>{Gray2Binary(Binary2Gray(i))} << " -> "
            << i
            << endl;
    }

	return 0x00;
}
