# Verilog bit indexing

A signal is defined as :

logic [width_x-1:0] x;


I want to assign x a value where the second bit from the top is '1' and all other bits are '0'. For example, if width_x is 4 then I want x to be "0100". In VHDL, it can be done as follows:

x<=(x'length-1=>'1',others=>'0');


What will be the closest Verilog/SV equivalent ?

• the VHDL one won't do precisely what you're asking either, unless the LSB is numbered 1 (not 0). You probably meant x'left-1=>'1' Sep 10 '20 at 16:09

Here's another method:

x <= {2'b01, {width_x-2{1'b0}}};


Or you can use bit shifting if width_x is relatively small:

x <= 1 << (width_x - 2);


Basically you need these 2 lines:
x = 0; // to set all bits to 0
x[width_x - 2] = 1'b1; // to set 2nd topmost bit to 1

Below is more complete code.

module aa;
parameter width_x = 14;

logic [width_x-1:0] x;

initial begin
$display("x = %b", x); #10 x = 0;$display("x = %b", x);
#10 x[width_x - 2] = 1'b1;
$display("x = %b", x);$finish;
end
endmodule