Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Format with '%u' print the wrong value when I give it a negative number?

Why does Format('%u', [-100]) result in '4294967196'? I tested this in D7 and XE2.

The documentation on the Format function says:

%u Unsigned decimal. Similar to %d, but no sign is output.

So I would have expected a result as '100'.

Is this a bug?

like image 947
NGLN Avatar asked Jul 02 '12 11:07

NGLN


1 Answers

No, this is not a bug.

You are telling Format that the first argument is an unsigned integer but in fact you passed a signed integer. That signed integer is being interpreted as unsigned and the bit pattern for a signed value of -100 equates to an unsigned value of 4294967196.

In fact your code is in error. The format string defines a contract that the compiler cannot enforce because the arguments to Format are weakly typed. It is your responsibility to make sure that when you promise to pass an unsigned value that you do indeed pass an unsigned value. The mistake in the code here is logically equivalent to passing a string or a floating point value which is an error which you will much more readily recognise.

like image 82
David Heffernan Avatar answered Oct 01 '22 13:10

David Heffernan