whitecat whitecat - 1 year ago 86
PHP Question

Using printf() function in PHP to print negative integer with unsigned format specifier

I have the following code:

$num1 = -12;
printf("%%u = %u<br>",$num1);


%u = 4294967284

I am unable to understand the reason behind such output.

Answer Source

Any unsigned type means >= 0 values.

Here is what the php docs say:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX since PHP 5.0.5, and minimum value using the constant PHP_INT_MIN since PHP 7.0.0.

I'm running it on Windows x64, so the value to PHP_INT_MAX will be a integer 64 bit long (9223372036854775807). From the value you are reporting, you probably have a 32 bit system.

So, for your system the signed 32 bit integer values range from -2147483648 to 2147483647. For unsigned values it goes from 0 to 4294967295.

Your value of 4294967284 is 4294967295 - 12 + 1.

Bottom line: you can safe cast regular int to unsigned int if it's a positive value. If it's a negative value, the cast will result in value generated by the above formula (MAX_UINT - value + 1). Signed and unsigned types are only compatible with positive values.

You can use an if clause for a proper signed format specifier for accurate printing of values.

Hope this clears out the problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download