64 bit Integer and PHP

Published in category Productivity and Programming
on Christian Mayer's Weblog.

While programming on my assembly project for PHP I discovered the limits of Integer numbers. For this purpose there is a reserved constant called PHP_INT_MAX and PHP_INT_SIZE. On 64-bit machines PHP_INT_MAX is 0x7fffffffffffffff. This is because the highest bit (posistion 63) is used as sign bit.

But what if you want to deal with a number like 0xffffffffffffffff? Of course you can use extensions like GMP or BCMath to deal with bigger numbers. What if you won’t to deal with numbers as strings rather than real numbers?

You cannot convert numbers greater than PHP_INT_MAX to Integer. They always will be 0. Everything else is converted to float/double.

There is no difference between notations. 0xffffffffffffffff is the same as 18446744073709551615. 255 is the same as 0xff and 0b11111111. But it’s a difference if you compare numbers. Especially big numbers. For example: 0x7f00ff | 0x800000 ends in the same result as 0xff00ff; but 0x7f000000000000ff | 0x8000000000000000 is not the same as 0xff000000000000ff. That’s because PHP interprets 0xff000000000000ff internally as a floating point number and 0x7f000000000000ff as an Integer.

So if you want to deal with 64-bit Integer you must use non-64-bit Integers with bitwise operators. For example: to build 0xfffffffffffffffe you can use (0xffffffff << 32) | 0xfffffffe.

More Resources

Recent Posts

About the Author

Christian is a professional software developer living in Vienna, Austria. He loves coffee and is strongly addicted to music. In his spare time he writes open source software. He is known for developing automatic data processing systems for Debian Linux.