What is the difference between Verilog ! and ~?

倾然丶 夕夏残阳落幕 提交于 2019-11-29 05:55:24

The ! symbol represents boolean or logical negation. For any value of x other than zero, !x evaluates to zero or false, and when x is zero, !x evaluates to one, or true.

The ~ symbol represents bitwise negation. Each bit in the value is toggled, so for a 16-bit x == 0xA5A5, ~x would evaluate to 0x5A5A.

The if() conditional expects an expression that evaluates to true or false, where anything nonzero (positive or negative) is true, and zero is false.

The && is a logical AND. It takes two expressions, evaluating to one or true if and only if both of the expressions are true. Again, "true" here means nonzero, positive or negative.

Given all this, we can see that the only time ~x and !x evaluate to the same value is when x == -1, or, if x is unsigned, when x == MAX_UNSIGNED.

I see. The variable "x" in the above code was a Verilog integer (integer x;). However, an integer variable is represented by Verilog as a 32-bit integer number. So even though x was "1" as I had observed, ~x will not result in "0" but in "11111111111111111111111111111110"! And so it's no surprise that the First Case was executed. My fault. Thanks for all the answers.

~ is a bit-wise operator and returns the invert of the argument.

! is a logical operator and returns a single bit.

Example:

reg [7:0] bit_wise, logic_op;
initial begin
  bit_wise = ~8'hA1; // bit_wise == 8'h6E
  logic_op = !8'hA1; // logic_op == 8'b00
  $display("bit_wise:%h logic_op:%h", bit_wise, logic_op); // bit_wise:5e logic_op:00
end

For your example:

if(~x && ~y) begin
    //do stuff
end

Is effectively the same as:

if(x!='1 && y!='1) begin // '1 means the with of x all 1s and the with of y all 1s
    //do stuff
end

Generally the best coding style is to use logical operators inside if statements. Only use bit-wise operators with data assignment manipulations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!