1

I'm looking for a concise way to convert a 8-char string to an 32-bit signed integer.

See the reference for Convert.ToInt32 method on MSDN.

This is the current .NET code in VB:

Convert.ToInt32("c0f672d4", 16)
// returns -1057590572

How can I get the same return value using PHP 5.3+ for both 32-bit and 64-bit?

I imagine it may require a combination of pack/unpack functions and bitwise operators but as yet have not found the right combination.

Updated: 2013-07-10 The following only works on 32-bit systems:

$str = 'c0f672d4';
$int = intval( substr( $str, 0, 4 ), 16 ); // read high 16 bit word
$int <<= 16; // shift hi word correct position
$int |= intval( substr( $str, 4, 4 ), 16 ); //  read low 16 bit word
echo $int;
// returns -1057590572

The problem with the above is that it does not work on 64-bit system. Instead I get the value 3237347344 using the above PHP code.

Any ideas for getting a consistent integer with PHP which is portable for 32-bit and 64-bit?

paperclip
  • 2,280
  • 6
  • 28
  • 39

2 Answers2

3

This is currently working for me on 32-bit and 64-bit systems, YMMV. Make sure you test, test, test!

credit: https://stackoverflow.com/a/2123458/

function intval_32bits($value)
{
    $value = ($value & 0xFFFFFFFF);
    if ($value & 0x80000000) $value = -((~$value & 0xFFFFFFFF) + 1);
    return $value;
}
Community
  • 1
  • 1
paperclip
  • 2,280
  • 6
  • 28
  • 39
1

You need to convert from 64 bit two's complement +ve val to a 32 bit two's complement -ve value

function to_int32($value) {

    $intval = hexdec($value);

    // If 64 bit
    if (PHP_INT_SIZE === 8) {
        return ($intval - 0x100000000);
    }

    // 32 bit
    return $intval;
}
Sam Giles
  • 650
  • 6
  • 16
  • I've tested this on both 32-bit and 64-bit and it appears to be working. Thank you. Do you have more information where I can read more on this fix / solution? – paperclip Jul 11 '13 at 08:47
  • Subsequently, I've come across some edge cases that didn't work out so I'm doing some more rigours testing with these two solutions: http://stackoverflow.com/a/2123458/156406 http://stackoverflow.com/a/8130131/156406 – paperclip Oct 28 '13 at 14:31