user2080473
user2080473

Reputation: 23

Byte to gigabyte conversion not working

Trying to convert 9769712680 Bytes to Gigabytes. I have the following code:

$value = 9769712680 / (1024 * 1024 * 1024);

This should give a value of 9 Gb but instead it gives 2047 Mb (or 2 Gb).

Also tried: 9769712680 / 1024 / 1024 / 1024 but this also does the same thing.

Any ideas?

Upvotes: 2

Views: 385

Answers (4)

HamZa
HamZa

Reputation: 14921

You may use the BCMath library:

$bytes = '976971268097697126809769712680976971268097697126809769712680';
$Gb = bcdiv($bytes, bcpow(1024, 3), 2);
echo $Gb; // 909875396730096197509923682250992368225099236822509.92

Upvotes: 0

dan-lee
dan-lee

Reputation: 14492

I don't know why this is not represented right (it does work for me).
Anyway you can use the BC Math library, which is commonly compiled with PHP, to solve equations with numbers of any length.

In your case it would look like this:

$value = bcdiv('9769712680', '1073741824', 4); /// 1024^3=1073741824

Upvotes: 0

Pursuit
Pursuit

Reputation: 12345

Looks like the initial number is represented as a int32. Doing some math (using Matlab):

9769712680/(1024*1024*1024) = 9.09875396639109

double(int32(9769712680))/(1024*1024*1024) = 2

Upvotes: 0

Andrey
Andrey

Reputation: 60065

9769712680 - you have integer overflow here, so it becomes 2^31, the max int value.

Upvotes: 5

Related Questions