views:

130

answers:

3

I'm running into a problem because my database has BIGINT data (64-bit integers) but the version of PHP I'm running is only 32-bit.

So when I pull out value from a table I end up with a numeric string representing a 64-bit integer in base 10. What I would ideally like to do is use the 64-bit integer as a bitmask. So I need to go to either two 32-bit integers (one representing the upper part and one the lower part) or a numeric string in base 2.

Problem is I can't just multiply it out because my PHP is only 32-bit. Am I stuck?

+5  A: 

You can use MySQL's bit shift operators to split the 64-bit integer into two 32-bit integers. So, you could select:

select (myBigIntField & 0xffffffff) as lowerHalf,
       (myBigIntField >> 32) as upperHalf
James McNellis
Oooh, that's beautiful. Why didn't I think of that? Note to self: Don't answer questions directly after getting up. +1
Joey
James, that's brilliant. Thanks! Unfortunately I just registered so I don't have any reputation to vote your answer up but it's perfect.
Brad
+1  A: 

To handle arbitrary size integers, you have two options in PHP: GMP and BC Math methods.

I believe GMP is more efficient by using some custom resources, while BC uses strings directly.

If you won't be processing too many (thousands or more) of numbers at a time, you may use BC directly.

Seb
+1  A: 

You have a few options here:

  1. Use either BCMath or GMP if they are included in your PHP installation. Both should provide arbitrary-length integers.
  2. Ask the database to convert the integer to a 64-character long bit string instead
  3. Write a bignum implementation yourself (more work :-))
Joey