Reverting unpack('C*', “string”)

女生的网名这么多〃 提交于 2019-12-19 18:53:17

问题


I would like to know how I can reverse what this unpack function bellow performed. I think the pack function is able to reverse what unpack performed, however I'm not sure.

First I have a simple string which after unpacking it I would have an array of bytes representing such string. Now I would like to know how to reverse such array back to the original string.

<?php
$array = unpack('C*', "odd string");
/*Output: Array
(
    [1] => 111
    [2] => 100
    [3] => 100
    [4] => 32
    [5] => 115
    [6] => 116
    [7] => 114
    [8] => 105
    [9] => 110
    [10] => 103
)*/

$string = pack("which format here?", $array);

echo $string;
#Desired Output: odd string
?>

Thank you.


回答1:


You should use call_user_func_array to revert unpack('C*', “string”), like this:

call_user_func_array('pack', array_merge(array('C*'), $array )))



回答2:


When you're on PHP 5.6, you should consider using argument unpacking as it is about 4 to 5 times faster than using call_user_func_array:

pack('C*', ...$array);

And when you're on PHP 5.5 or lower, you should consider using ReflectionFunction, which seems to be a bit faster than call_user_func_array:

$packFunction = new ReflectionFunction('pack');
$packFunction->invokeArgs(array_merge(array('C*'), $array));


来源:https://stackoverflow.com/questions/18357008/reverting-unpackc-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!