/***************************** GRAY.CPP ***************************************
* Example showing the use of bit-wise operators                    1998-10-01 *
*                                                                   Agner Fog *
*                                                                             *
* The program converts a decimal integer to binary and gray code.             *
* Gray code is defined in your hardware book: J. F. Wakerly: Digital Design,  *
* 2' ed., page 47.                                                            *
* Bit number i in the gray code is equal to the XOR combination of bit number *
* i and bit number i+1 in the binary code. This conversion is done by the     *
* function gray.                                                              *
*                                                                             *
******************************************************************************/
#include <iostream.h>
#include <conio.h>

int gray (int b)
// Convert binary to gray code by XOR'ing each bit with the bit above.
// The operator ^ is bitwise XOR. The operator >> is shift left
{
   return b ^ (b >> 1);
}

void binout (int b)
// Outbut b to the screen as a binary number by writing one binary digit at
// a time. The operator >> is shift left. The operator & is bitwise AND.
{
   for (int i=15; i>=0; i--)
   {
      cout << ((b >> i) & 1);
   }
}

void main()
{
   int b;
   clrscr();  // clear screen
   cout << "\n\nPlease enter an integer ";
   cin >> b;
   cout << "\nBinary code = ";
   binout(b);
   cout << "\nGray code =   ";
   binout(gray(b));
   getch();  // wait for key pressure
}
