HDLBits – Vector2

A 32-bit vector can be viewed as containing 4 bytes (bits [31:24], [23:16], etc.). Build a circuit that will reverse the byte ordering of the 4-byte word.

This operation is often used when the endianness of a piece of data needs to be swapped, for example between little-endian x86 systems and the big-endian formats used in many Internet protocols.

Hint: Part-select can be used on both the left side and right side of an assignment.

https://hdlbits.01xz.net/wiki/Vector2

The important thing to note in this exercise is that we are byte-swapping the input and not bit-swapping. Since there are 8 bits in a byte, in order to achieve this goal, will have to chop the input into 4 separate byte segments. The first way that we could do this is to use part select, described in the last exercise, and drive segments of the output in separate assign statements:

module top_module ( 
  input logic  [31:0] in,
  output logic [31:0] out );
  // Byte swapping using part select and multiple assignments
  assign out [31:24] = in  [7:0];
  assign out [23:16] = in [15:8];
  assign out  [15:8] = in[23:16];
  assign out   [7:0] = in[31:24];
endmodule : top_module

Pop quiz! What would happen if we did the following?

module top_module ( 
  input  logic [31:0] in,
  output logic [31:0] out );
  // Byte swapping using part select and multiple assignments
  assign out [31:24] = in  [7:0];
  assign out [23:16] = in [15:8];
  assign out  [15:8] = in[23:16];
  assign out     [7] = in    [0]; // NEW CODE
  assign out   [7:0] = in[31:24];
endmodule : top_module

As was described in the last exercise, the logic datatype cannot have multiple drivers. In this case, out[7] is being driven twice, which will cause a compilation error.

We can also solve this problem with concatenation and part select:

module top_module ( 
    input logic  [31:0] in,
    output logic [31:0] out );
    
    // Byte swapping using concatenation and part select
    assign out = {in[7:0], in[15:8], in[23:16], in[31:24]};
endmodule : top_module

Leave a Reply

Your email address will not be published. Required fields are marked *