Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is -13 % 64 = -13 in PHP?

Tags:

php

math

modulus

Derived from this question : (Java) How does java do modulus calculations with negative numbers?

Anywhere to force PHP to return positive 51?

update
Looking for a configuration setting to fix, instead hard-guessing

Or other math function like bcmath?

updated
Not entire convinced by that java answer, as it does not take account of negative modulus -13+(-64) =?

like image 574
ajreal Avatar asked Dec 10 '10 13:12

ajreal


People also ask

How Base64 encode in PHP?

Syntax. base64_encode() function can encode the given data with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean such as mail bodies. Base64-encoded data can take about 33% more space than original data.

What is 64 format?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

How many bits is a base-64?

BASE64 characters are 6 bits in length. They are formed by taking a block of three octets to form a 24-bit string, which is converted into four BASE64 characters.


3 Answers

Anyway, the post you referenced already gave the correct answer:

$r = $x % $n;
if ($r < 0)
{
    $r += abs($n);
}

Where $x = -13 and $n = 64.

like image 132
Spiny Norman Avatar answered Nov 15 '22 18:11

Spiny Norman


If GMP is available, you can use gmp_mod

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Example:

echo gmp_strval(gmp_mod('-13', '64')); // 51

Note that n and d have to be GMP number resources or numeric strings. Anything else won't work¹

echo gmp_strval(gmp_mod(-13, 64));
echo gmp_mod(-13, 64);

will both return -51 instead (which is a bug).

¹ running the above in this codepad, will produce 51 in all three cases. It won't do that on my development machine.

like image 44
Gordon Avatar answered Nov 15 '22 19:11

Gordon


The modulo operation should find the remainder of division of a number by another. But strictly speaking in most mainstream programming languages the modulo operation malfunctions if dividend or/and divisor are negative. This includes PHP, Perl, Python, Java, C, C++, etc.

Why I say malfunction? Because according to mathematic definition, a remainder must be zero or positive.

The simple solution is to handle the case yourself:

if r < 0  then r = r + |divisor|;

|divisor| is the absolute value of divisor.

Another solution is to use a library (as @Gordon pointed). However I wouldn't use a library to handle a simple case like this.

like image 42
Nylon Smile Avatar answered Nov 15 '22 19:11

Nylon Smile