0

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..

bijlikamasla
  • 371
  • 3
  • 6
  • 11
  • 2
    Is this homework? What all have you tried so far ? – codaddict Feb 06 '11 at 18:35
  • no, its basically a long code. this is just a snippet of what. What i am not understanding is that, how to change only one bit at a time and generate series, like its done in gray's code? i can convert it to array of intergers but what next? – bijlikamasla Feb 06 '11 at 18:47
  • See Oli's answer below - it's very easy to convert an integer to its corresponding Gray Code representation – Paul R Feb 06 '11 at 18:49
  • i want to do something like, for example 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.. – bijlikamasla Feb 06 '11 at 19:16

1 Answers1

4

It can be as simple as:

x_gray = x ^ (x >> 1);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 1
    @bijlikamasla: Sounds like you need to go look up [bitwise operators in C](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Bitwise_operators). That's not exponentiation. – Cascabel Feb 06 '11 at 18:56
  • i want to do something like, for example 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. – bijlikamasla Feb 06 '11 at 19:19
  • @bijilk: That doesn't make any sense. Are you just asking for a gray-code counter? – Oliver Charlesworth Feb 06 '11 at 19:23
  • yeah, sort of, but for char array.. not integer array. – bijlikamasla Feb 06 '11 at 19:28
  • @bijilk: Then please update your question to make it clear *exactly* what you're trying to do. If you want to make a counter, then *say so*! – Oliver Charlesworth Feb 06 '11 at 19:30