Search code examples
phppack

What is reverse action for pack('V') in PHP?


I saw a code like this:

$len = strlen($str1);
$str = pack('V', $len) . $str1 . $str2;

What will be the code for doing the reverse thing?

As far, as I understand, the first step would be:

$len = substr($str, 0, 4);
$str = substr($str, 4);

But what is next?

$len = unpack(???);
$str1 = substr($str, 0, $len);
$str2 = substr($str, $len);

I don't quite understand how am I supposed to convert binary $len back to... binary integer? I would use a simple typecast or memory copy in the usual languages, but I am new to PHP.


Solution

  • It's just a case of removing the extra string added here

    $str = pack('V', $len) . $str1 . $str2;

    and unpacking the rest.

    Example:

    // your code
    $len = strlen($str1);
    $str = pack('V', $len) . $str1 . $str2;
    
    // unpacking
    $length_of_packed_string = strlen($str) - strlen($str1 . $str2);
    $unpacked = unpack('V', substr($str, 0, $length_of_packed_string));
    
    print_r($unpacked);
    

    Note that this returns an array, with your value at index 1 (the only index) - so $unpacked[1]. See the notes section on the unpack manpage for more info on why.

    https://3v4l.org/dgWR9