views:

69

answers:

2

I was simply wishing to test for overflow on an integer, such as in C (well, if it were just over integer max anyway). When I looked to see if PHP was actually doing what I told it to, it seems it fails for some reason. Here are my tests of the problem:

define('INT_MAX', 0x7FFFFFFF);
print "In decimal: " . hexdec(INT_MAX) . "<br/>";
print "In decimal: " . hexdec(0x7FFFFFFE) . "<br/>"; //Under int_max
print "In hex: " . dechex(hexdec(INT_MAX)) . "<br/>";
print "Float: " . ((bool)is_float(INT_MAX)?'true':'false') . "<br/>";

Results being:

In decimal: 142929835591
In decimal: 142929835590
In hex: 47483647
Float: false

As I saw on the manual, it will cast to float if overthrown, but it seems to not and is clearly way higher. Am I being insane and missing something here, or is there some odd problem I should really need to know about when working with hexidecimal in PHP?

A: 
define('INT_MAX', 0x7FFFFFFF);

This defines INT_MAX to be integer 2147483647. It is unnecessary to interpret it as a hexadecimal number. If you really want to use INT_MAX as a literal hexadecimal value, then you need to declare it as '7FFFFFFF' (inside a string); then the hexdec function will interpret the hexadecimal notation and convert it to a decimal value.

print(dechex(INT_MAX) . "\n");

This prints "7fffffff".

amphetamachine
I wasn't aware that the hexadecimal notation only stored it in decimal in the end. I was just reconverting it from hex incorrectly, thanks!
John
+2  A: 

Your program makes no sense, because you are taking 0x7FFFFFFF which is 2147483647, and then treating it like 0x2147483647, which is 142929835591 in decimal.

Anyway, PHP already has a constant that you can use:

var_dump(PHP_INT_MAX + 1); // converted to float
konforce