1
module binarytogray #(
 parameter PTR=2
)(
 input  logic [PTR:0] binary_value,
 output logic [PTR:0] gray_value
);

genvar i;    
generate
for(i=0;i<PTR;i=i+1) begin:for_loop
  assign gray_value[i]=binary_value[i]^binary_value[i+1];
end
endgenerate

  assign gray_value[PTR]=binary_value[PTR];
endmodule

This binary to gray conversion code is an example from a book. Can anybody explain:

assign gray_value[i]=binary_value[i]^binary_value[i+1];

I am not able to understand this specific XOR operation for converting to gray code from binary.

Example on EDAplayground.

Morgan
  • 19,934
  • 8
  • 58
  • 84
Vaibhav Sundriyal
  • 567
  • 5
  • 11
  • 18
  • 2
    I think this is a good question (please do not delete it), but it would be good if you showed what you had tried. – Morgan Feb 20 '14 at 09:17
  • Very detailed explanation: https://marcin-chwedczuk.github.io/binary-to-gray-algorithm-explained – csharpfolk Dec 18 '19 at 08:50

5 Answers5

2

The ^ is an XOR (exclusive or) operator.

A B | Result
----+-------
0 0 |  0
0 1 |  1
1 0 |  1
1 1 |  0

The i's are just indexes for current and last position in the loop.

The (unary) Xor can also be used as a reduction operator to generate parity of words:

^4'b0001 => 1'b1
^4'b0101 => 1'b0
Morgan
  • 19,934
  • 8
  • 58
  • 84
2

A more compact solution (though functionally identical) is this:

assign gray_value[PTR:0] = binary_value[PTR:0] ^ {1'b0, binary_value[PTR:1]};

This avoids the generate block and the loops but still does the bitwise XOR on all of the bits except the MSB.

Where you do need the loop is going in the other direction (gray to binary):

always_comb begin
  binary_value[PTR] = gray_value[PTR];

  for(int i=PTR-1; i>=0; i--) begin
    binary_value[i] = gray_value[i] ^ binary_value[i+1];
  end
end
nguthrie
  • 2,615
  • 6
  • 26
  • 43
1

This is just the way the conversion works. If you follow this image, you'll see basically the same operation as your Verilog code.

0

Simple Binary to gray conversion Data flow Model Verilog code:

module bintogray(input [3:0]bin,output [3:0]gray);

assign gray[3] = bin[3];

assign gray[2] = bin[3]^bin[2];

assign gray[1] = bin[2]^bin[1];

assign gray[0] = bin[1]^bin[0];

endmodule

-1

Try this code

module B2G (binary_value, gray_value);
  input [7:0] binary_value;
  output [7:0] gray_value;

  genvar i;
  generate
    for(i=6; i>=0; i=i-1)
    begin

    assign gray_value[i] = binary_value[i+1] ^ (binary_value[i]);
  end
endgenerate

assign gray_value[7] = binary_value[7];
endmodule
Arseniy Zhizhelev
  • 2,381
  • 17
  • 21
Manish
  • 1