What is the difference between single (&) and double (&&) ampersand binary operators?

非 Y 不嫁゛ 提交于 2019-12-06 11:38:35

问题


In IEEE 1800-2005 or later, what is the difference between & and && binary operators? Are they equivalent?

I noticed that these coverpoint definitions behave identically where a and b are of type bit:

  • cp: coverpoint a & b;
  • cp: coverpoint a && b;

回答1:


&& is a boolean operator which we call "logical AND". This doesn't mean that it must operate on boolean operands, but that its return type is boolean. In SV, boolean means:

1'b1 \\ true
1'b0 \\ false
1'bx \\ undef

When logical AND operates on single bit operands the result is obvious, but the issue arises when it operates on a vector. For example:

logic [1:0] vector;
...
vector = 2'b10;
if (1'b1 && vector) ...

For purpose of this logical operation, vector is tested for equality to 0. If it is, then its boolean value is defined as "false", otherwise "true". In the above example, the result is "true".

& is a bitwise AND and reduction AND operators. Whether it is executed as bitwise or reduction is determined by the context:

logic [1:0] vector1;
logic [1:0] vector2;
logic [1:0] vector3;
...
vector1 = 2'b10;
vector2 = 2'b01;
...
vector3 = vector2 & vector1; // bitwise; vector3 = 2'b00
if ( (&vector1) || (&vector2) ) ... // reduction; the result of each reduction is 1'b0

Bitwise operator performs logical AND operation on each pair of corresponding bits of operands. The result is a vector which width equals to maximal width of operands.

Reduction operator performs logical AND operation between all the bits of a single vector. The result is a single bit boolean value.

NOTE: when executed on a single bit operands, the results of bitwise and logical operators are the same. However, when even one of the operands is a vector, the results may differ.




回答2:


&& is logical AND. It accepts two booleans and returns boolean.

& is bitwise AND. It accepts two numbers and returns a number.

In the above example, the behavior would be different if a and b where both packed bit [1:0].



来源:https://stackoverflow.com/questions/17327680/what-is-the-difference-between-single-and-double-ampersand-binary-opera

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