Chong Han
Chong Han

Reputation: 41

What is the best way to write bit number in Verilog?

For writing the bit in Verilog, which is better in the following writing:

Let's say 32 bits data and all 32 bits are set to zero:

1) 32'b0

or

2) 32{1'b0} ?

On the other hand, i want to change 5 MSB bit to one:

1) {5'b1,26'b0}

or

2) {5{1'b1},26{1'b0}}

1 or 2 is better? Or they are behave the same? Thanks in advance.

Thanks
Chong Han

Upvotes: 1

Views: 11439

Answers (1)

dave_59
dave_59

Reputation: 42788

Verilog has good and evil ways of dealing with bit widths of expressions. On the one hand, you can easily assign an expression of a certain width to a variable of another width, and it automatically pads or truncates the expression to fit into the variable. On the other hand, you can assign an expression of a certain width to a variable of another width, and it silently pads or truncates the expression to fit into the variable.

In SystemVerilog, if you want to set all bits of a variable to 0, you write

VariableName = '0;

The expression '0 will be sized to the context of the variable it is being assigned to. There is no need to declare a specific width. But even if you wrote

VariableName = 0;

There is no need to size the 0 because it gets truncated or padded with 0's to fit into variable. There's no difference in the first 2 expressions you wrote. It comes down to how you view the value as a integral number, or a set of 32 individual bits.

The second two expressions do not represent the same value. {5'b1,26'b0} is 32'h0800_0000 and {5{1'b1},26{1'b0}} is 32'hF800_0000. If you are really looking to set a single bit position, most people order their bits from the LSB starting at 0, and would write something like 32'b1 << 26.

Upvotes: 9

Related Questions