Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

boolean logic - What is the difference between Verilog ! and ~?

So it ended up that the bug that had kept me on for days, was a section of code that should have evaluated to False evaluating to True. My initial code went something like:

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

i.e. If x is NOT ONE and y is NOT ONE then do stuff. Stepping through the debugger, I realized even though x was 1 the expression in the if-statement still resulted into TRUE and the subsequent code was executed.

However, when I changed the statement to:

if(x == 0 && y == 0) begin
//do stuff
end

and also tried:

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

the code within the if-statement was not evaluated which was the expected behaviour. I understand that ~ is a bitwise negation and ! a logical negation, but shouldn't (~x && ~y) and (!x && !y) evaluate to the same thing? I'm afraid the codebase is too large, so I can't paste it here, but this was the only alteration I made to make the code to work as I intended. Thanks.


In response, to one of the comments below, I have created a test-case to test this behaviour:

`timescale 10ns/1ns

module test_negation();
        integer x, y;

    initial begin
        x = 1; y = 0;

        if(~x && ~y) begin
            $display("%s", "First case executed");
        end

        if(!x && !y) begin
            $display("%s", "Second case executed");
        end

        if(x == 0 && y == 0) begin
            $display("%s", "Third case executed");
        end
    end endmodule

And strangely enough, "First case executed" is printed to confirm the original behaviour I observed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...