bijlikamasla
bijlikamasla

Reputation: 371

Convert a character array of binary numbers into a counter of Gray Code in C++

is there any way to convert a char array of binary number into Gray Code. For example, I have the following code:

int j;
char binaryNum[10], *pointer;
/* From Hex convert to decimal */
j = strtol( str, &pointer, 16);
/* From Decimal convert to Binary */
itoa(j, binaryNum, 2);
cout<<"Binary form of Y = "<<binaryNum<<"\n";

What i want is to convert this binaryNum into Gray Code, i.e change it one bit at a time. Can somebody please help me with the code ? forexample, i have a char binaryNum[10] == 101101 and i want to convert it to gray code, i.e change only one bit at a time, like: 101100 101110 101111 something like thiss..

Upvotes: 0

Views: 1402

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

It can be as simple as:

x_gray = x ^ (x >> 1);

Upvotes: 4

Related Questions