modular arithmetic in PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
withnail
Forum Newbie
Posts: 1
Joined: Wed Jan 21, 2009 8:54 am

modular arithmetic in PHP

Post by withnail »

Hi All,
In the C based languages they have a type called a ulong.
As you probably know this is a 64 bit value and can therefore hold upto 18,446,744,073,709,551,615.
If you overload this 64bit limit the ulong resets and starts from 0 again in a modular kind of way I think.

i.e. if you made a ulong called ulong1 and made it equal 18,446,744,073,709,551,615 and then you added 4 to it would end up having the value 3 (it starts counting again from zero).

Is there any such storage container in PHP that acts in this fashion, I have been checking the documentation but cannot see anything.

My only other option is to recreate a binary arithmetic system using arrays of bits and ignoring bits beyond the 64th but this seems a bit ovet the top.

Any ideas greatly appreciated.
W
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: modular arithmetic in PHP

Post by VladSun »

Check this out:

http://bg.php.net/manual/en/reserved.constants.php
PHP_INT_MAX (integer)
Available since PHP 4.4.0 and PHP 5.0.5
PHP_INT_SIZE (integer)
Available since PHP 4.4.0 and PHP 5.0.5
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: modular arithmetic in PHP

Post by VladSun »

Hm ...
Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: modular arithmetic in PHP

Post by requinix »

Let me say now: if you're relying on behavior like that then you're already having problems.
PHP abstracts out data types. Since you're relying on the nature of the type then you'll have problems trying that same logic with PHP.

All I can tell you is to use the modulus operator, and that PHP will regard large integers as floating-points. You will start losing precision.

Code: Select all

$i = 5555555555555555555;
echo $i%5; // -3 on my AMD x64 system
 
// The solution is the bcmath extension
// http://php.net/manual/en/ref.bc.php
 
$i = "5555555555555555555";
echo bcmod($i, "5"); // 0
Post Reply