Prev Problem
Next Problem

17. Binary to Gray Code Converter

module bin2gray4 (
    input  [3:0] bin_in,
    output [3:0] gray_out
);
    // Compact vector form (logical shift right)
    assign gray_out = bin_in ^ (bin_in >> 1);

endmodule

💡Remember

  • Vector trick: bin ^ (bin >> 1) implements Binary→Gray in one line.
  • Bitwise vs reduction: ^ here is bitwise XOR (vector result), not reduction XOR (^bin).
  • Indexing matters: LSB depends on two adjacent bits (bin[1] ^ bin[0]), MSB copies through.
  • Sized literals: Use 4'h* in tests to avoid width surprises.
  • Pure combinational: No always needed—continuous assign is enough.