Write a SystemVerilog code for a 4×2 priority encoder.

Sure, here’s an example of a 4×2 priority encoder implemented using SystemVerilog:

module priority_encoder_4x2(
  input logic [3:0] in,
  output logic [1:0] out,
  output logic valid
);

  always_comb begin
    casez(in)
      4'b0001: begin out = 2'b00; valid = 1; end
      4'b001x: begin out = 2'b01; valid = 1; end
      4'b01xx: begin out = 2'b10; valid = 1; end
      4'b1xxx: begin out = 2'b11; valid = 1; end
      default: begin out = 2'b00; valid = 0; end
    endcase
  end

endmodule

In this code, we define a module called `priority_encoder_4x2` with one input port `in`, which is a 4-bit binary value representing the priority encoder inputs, and two output ports `out` and `valid`. The `out` output is a 2-bit binary value representing the highest priority input, and the `valid` output is a single-bit binary value representing whether there is a valid input signal.

The `always_comb` block is used to describe the behavior of the priority encoder. The `casez` statement uses a case statement with don’t care (`x`) values to match the input signal with the highest priority input.

For example, if the input signal `in` is `4’b0100`, the output signal `out` will be set to `2’b01`, which represents the position of the highest priority input signal (the second input signal). The `valid` signal will be set to 1 to indicate that there is a valid input signal.

If multiple input signals are asserted, the priority encoder encodes the input signal with the highest priority (the input signal with the highest position in the binary value `in`).

If no input signals are asserted, the priority encoder sets the `out` output to `2’b00` and the `valid` output to 0 to indicate that there is no valid input signal.

You can instantiate this module in your top-level design hierarchy and connect it to other modules or input/output signals as needed. Note that you can modify the code to implement a priority encoder with a different number of inputs by changing the bit width of the input signal and the output binary value, and modifying the priority encoding logic accordingly.