Gray Series - Converting To and From Gray Code

Converting To and From Gray Code

The following functions in C convert between binary numbers and their associated Gray codes.

/* The purpose of this function is to convert an unsigned binary number to reflected binary Gray code. The operator >> is shift right. The operator ^ is exclusive or. */ unsigned int binaryToGray(unsigned int num) { return (num >> 1) ^ num; } /* The purpose of this function is to convert a reflected binary Gray code number to a binary number. */ unsigned int grayToBinary(unsigned int num) { unsigned int numBits = 8 * sizeof(num); unsigned int shift; for (shift = 1; shift < numBits; shift = 2 * shift) { num = num ^ (num >> shift); } return num; }

Read more about this topic:  Gray Series

Famous quotes containing the words converting, gray and/or code:

    “A way of certifying experience, taking photographs is also a way of refusing it—by limiting experience to a search for the photogenic, by converting experience into an image, a souvenir. Travel becomes a strategy for accumulating photographs.”
    —Susan Sontag (b. 1933)

    “I had a good talk with Alcott this afternoon. He is certainly the youngest man of his age we have seen,—just on the threshold of life. When I looked at his gray hairs, his conversation sounded pathetic; but I looked again, and they reminded me of the gray dawn.”
    —Henry David Thoreau (1817–1862)

    “Many people will say to working mothers, in effect, “I don’t think you can have it all.” The phrase for “have it all” is code for “have your cake and eat it too.” What these people really mean is that achievement in the workplace has always come at a price—usually a significant personal price; conversely, women who stayed home with their children were seen as having sacrificed a great deal of their own ambition for their families.”
    —Anne C. Weisberg (20th century)