开发者

PHP: on 32 bit system INT_MAX displays wrong?

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: 开发者_如何学Go" . 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?


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


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜