Electronic – How to truncate an expression bit width in Verilog

verilog

Consider an expression like:

assign x = func(A) ^ func(B);

where the output of the func is 32 bits wide, and x is a wire of 16 bits. I want to assign only the lowest 16 bits of the resulting xor.

I know the above code already does that, but it also generates a warning. The "obvious" approach doesn't work:

assign x = (func(A) ^ func(B))[15:0]; // error: '[' is unexpected

Best Answer

You can use another variable, though this is not particularly elegant.

wire[31:0] y;

assign y = func(A) ^ func(B);
assign x = y[15:0];

A better approach would be to use a function.

function [15:0] trunc_32_to_16(input [31:0] val32);
  trunc_32_to_16 = val32[15:0];
endfunction

assign x = trunc_32_to_16(func(A) ^ func(B));