Convert from 64bit number to 32bit number

Trying a lot and just failing..

$x = 76561198005785475;

I want to this number, turn into this:

$y = 45519747;

That is the 32bit form of it.


Trying to explain with more details:

http://www.tonymarston.net/php-mysql/converter.php

1) Put the value 76561198005785475 on the “Decimal (input)” field.
2) Press “DEC to BIN” on the “Binary (Base 2)” field.
3) Count 32 starting from the RIGHT and copy it.
4) Paste the 32 chars binary number on “Binary (Base 2)” field.
5) Press “Bin to Dec” button on the “Binary (Base 2)” field.

Ok, now you can see the “45519747” number.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Try this:

$y = $x & 0xffffffff;

This will truncate your 64-bit value to a 32-bit value, but note that there is absolutely no way to get the 64-bit value back, this is a destructive method.

Solution 2

I tried many solution. But no one help me. Finally, following script save my life.

function intval32bits($value)
{
    $value = ($value & 0xFFFFFFFF);

    if ($value & 0x80000000)
        $value = -((~$value & 0xFFFFFFFF) + 1);

    return $value;
}

Solution 3

This is too long to write into a comment, so I’ll post it here instead.

@Kolink has the right answer; what you want is that operation. However, note that because your $x is too big to be stored in an int format anyway, it’ll be held as a float in 32-bit computers, and floats suffer from precision loss. My pet theory on why you get 45519744 instead of the right answer is that your 32-bit computer lost the precision on the last digits. To see this in action, try this here:

$x = 76561198005785475;
echo (int)$x;

That site uses a 32-bit server, and it returns 45519744. This demonstrates the precision loss.

On the other hand, if you go here and run:

$x = 76561198005785475;
$y = $x & 0xffffff;

You get the right answer, because that site is 64-bit.

If you want to do the operation on a 32-bit machine (as you evidently do), I suggest you use gmp_and from the PHP GMP extension. Unfortunately I couldn’t test to see if it works – I’ll leave that to you.

Solution 4

I had something similar. I was want to consider Overflow when converting from Int64 to Int32. this code worked well for me:

function intval32bits($value)
{
    $value = ($value & 0xFFFFFFFF);

    if ($value & 0x80000000)
        $value = -((~$value & 0xFFFFFFFF) + 1);

    return $value;
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply