4

I have negative binary number which has a sign bit and want to write a program to get its gray code. However, I can only find the solution for positive number. So here I am asking this question. Thanks.

  • What do you want the negative codes to look like? Just treating your numbers are unsigned will give you at least something (that is, you can convert to gray code and then back and you'll have the original number). – harold Nov 21 '14 at 09:25

2 Answers2

0

Gray code can only be calculated for non-negative numbers, using the following method:

int gray_encode(int n) {
    return n ^ (n >> 1);
}

The same method won't work for negative numbers because of Two's complement representation of binary numbers.

syntagma
  • 23,346
  • 16
  • 78
  • 134
  • Do I prove it to answer the question? – syntagma Nov 23 '14 at 10:20
  • Well I mean the whole two's complement deal means that there is no difference between large positive numbers and negative number, so if anything you've proved that it *is* possible – harold Nov 23 '14 at 10:28
0

It is possible to convert a signed integer to Gray code if the target bit width is known:

int gray_encode(int n) {
    return n ^ (n >> 1);
}

int gray_encode_signed(int n, int width_bits) {
    int all_ones = (1 << width_bits) - 1;
    return (n >= 0 ? gray_encode(n) : gray_encode(abs(n)) + all_ones);
}

For example, this is 4 bits Gray code for values from -7 to 7:

decimal   4bit gray code
     -7    1011
     -6    1100
     -5    1110
     -4    1101
     -3    1001
     -2    1010
     -1    1000
      0    0000
      1    0001
      2    0011
      3    0010
      4    0110
      5    0111
      6    0101
      7    0100
Alexey Polonsky
  • 1,141
  • 11
  • 12