Test your digital arithmetic - $urandom returns unsigned or signed?
SystemVerilog adds $urandom – a simple random number generator that returns a 32-bit UNSIGNED integer. Contrast it to good old $random – returns a 32-bit SIGNED integer.
Consider the below code snippet:
integer address;
initial begin : b1
address = $urandom;
$display (“%m address: %d”, address); end : b1
When you run the above code in Questa, one in a while you get:
# address = 90095195;
# address = -949724053;
First sight it looks strange, why is $urandom generating a negative number? Bug in the tool? Crazy? (See a real user post at: http://goo.gl/yp0WZ)
A bit of thinking, taking eyes away from monitor screen would help – follow your basics on digital arithmetic:
- integer – a signed 32-bit number (in Verilog)
- i.e. holds−2(n−1) through 2(n−1)−1. (2’s complement representation)
- So if you assign even a 32-bit UNSIGNED number with the MSB set to 1 – it will be treated as “signed 31-bits”
- Hence –> $urandom does generate 32-bit UNSIGNED, but when you assign it to a 32-bit signed integer, be ready for a surprise.
Not convinced yet? We at CVC like that attitude – be rebellious. Try the below code yourself. Notice we made address a 33-bit signed number, run it for yourself in a good simulator.
Send your comments via info@cvcblr.com for now (till we fix a hacker’s entry into our WP).
Comments
Post a Comment