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.
how to convert a negative binary number to its gray code
1.9k views Asked by Albert Zhou At
2
There are 2 answers
0
On
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
Gray code can only be calculated for non-negative numbers, using the following method:
The same method won't work for negative numbers because of Two's complement representation of binary numbers.