Professional Documents
Culture Documents
The Gray Code
The Gray Code
In this article, were going to develop a simple Matlab algorithm to make conversions between (from/to) binary and gray codes.
The most significant bit (MSB) in Gray is taken directly from the MSB in binary. The rest of the Gray bits comes from a xor operation between the precedent binary bit(b(i-1)) and the current binary bit (b(i)). In the case shown in the figure above:
g(1) = b(1) g(2) = b(1) xor b(2) g(3) = b(2) xor b(3) g(4) = b(3) xor b(4) g(5) = b(4) xor b(5)
The xor operation produces a 1 if the bits are different, and produces a 0 if the bits are equal. So, a binary 11101 becomes a 10011 in Gray.
Lets propose a code in Matlab to do it. function g = bin2gray(b) g(1) = b(1); for i = 2 : length(b); x = xor(str2num(b(i-1)), str2num(b(i))); g(i) = num2str(x); end
The input parameter to this function is a binary number (expressed in a string), the output is the equivalent Gray number (also expressed as a string). g g g g = = = = bin2gray('11101') bin2gray('10010') bin2gray('11110') bin2gray('10000')
We also can test a full sequence. We go from decimal-to-binary (using built-in function dec2bin) and then to Gray (using our developed function), for example: for d = 0 : 15 b = dec2bin(d); g = bin2gray(b); disp({d b g}) end
The results are (decimal, binary, gray): [0] [1] [2] [3] [4] [5] [6] [7] [8] '0' '0' '1' '1' '10' '11' '11' '10' '100' '110' '101' '111' '110' '101' '111' '100' '1000' '1100'
The most significant bit (MSB) in binary is taken directly from the MSB in Gray. The rest of the binary bits comes from a xor operation between the precedent binary bit (b(i-1)) and the current Gray bit (g(i)). In the case shown in the figure above: b(1) = g(1) b(2) = b(1) xor g(2) b(3) = b(2) xor g(3) b(4) = b(3) xor g(4) b(5) = b(4) xor g(5)
function b = gray2bin(g) b(1) = g(1); for i = 2 : length(g); x = xor(str2num(b(i-1)), str2num(g(i))); b(i) = num2str(x); end
And now we test a full sequence, going decimal-to-binary, binary-to-gray, and gray-tobinary:
We get (decimal, gray, binary): [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] '0' '0' '1' '1' '11' '10' '10' '11' '110' '100' '111' '101' '101' '110' '100' '111' '1100' '1000' '1101' '1001' '1111' '1010' '1110' '1011' '1010' '1100' '1011' '1101' '1001' '1110' '1000' '1111'