GManz
GManz

Reputation: 1659

PHP string to "unsigned long" (from C++)

I have this code in C++, which returns outputs the following number

int main(int argn, char** argv)
{
    cout << (*((unsigned long*)"P3TF")) << endl;
    cin.get();
    return 0;
}

How can I achieve the above in PHP (i.e. the string "P3TF" in unsigned long int). I tried using the pack method:

<?php
$lol = pack('N', 'P3TF');
var_dump( $lol, // returns jumbled up characters
          ord($lol[0]), // returns int 0
          ord($lol[1]), // returns int 0
          ord($lol[2]), // returns int 0
          ord($lol[3]), // returns int 0
          ord($lol[0]).ord($lol[1]).ord($lol[2]).ord($lol[3]) // returns 4 zeros as a string.
);
?>

I need it in bigendian byte order so I haven't used pack('V') or pack('L').

Anyone know how to achieve this?

Thanks!

Upvotes: 0

Views: 1314

Answers (1)

Phil Lello
Phil Lello

Reputation: 8639

If it's literally "P3TF" in the real code, why not convert it once, and define a constant in the PHP code?

Failing that, you need unpack, not pack. e.g. running

<?php
$in = 'P3TF';
$arr = unpack('N', $in);
printf("%08x\n", $arr[1]);
?>

Gives 50335446, which is the ASCII codes for 'P' '3' 'T' 'F' in hex (concatenated)

Upvotes: 1

Related Questions