Integer conversion issue.

So, there are some issues with pack and upack when dealing with unsigned 32-bit integers. The docs state that formats L, V and N are all unsigned numbers. However, on 32-bit PHP, there is no such thing as an unsigned 32-bit number. So, to get around it there you need to do something like this.

$strInt = sprintf("%u", $int);

That gives you a string of the unsigned integer. Now, you can’t bit shift it or do any numeric operations on it. But, you can use the bcmath functions with it and use it in output. So, it is quite useful.

However, the real problem for me is coming on 64-bit machines. More and more of our servers are 64-bit. On 64-bit machines, the above code gives you some odd 64-bit unsigned integer. Not the 32-bit integer that pack/unpack was supposed to return. So, now, how do I convert a 32-bit wrapped signed integer to a 64-bit unsigned integer? Well, I don’t know. I am hoping one of you as the answer.

FWIW, there is an active bug report on the pack/unpack issue. I tried looking through the code, but my C is just not up to snuff enough. So, to whoever ends up fixing this, thanks. I really appreciate it.


One Response to Integer conversion issue.

  1. Ren says:

    The way I deal with 32 bit unsigned values is

    if ($value < 0)
    $value += 0x100000000;

    If the value is unexpectedly negative, (ie 32 bit unsigned on a 32bit OS) the addition corrects the value, and implicitly casts value to a float. That way can still perform arthimetic without bcmath. The one gotcha is the modulus operator (%), have to use fmod() for floats.

%d bloggers like this: