Reverting unpack('C*', "string")
Asked Answered
E

2

7

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.

Emulate answered 21/8, 2013 at 12:7 Comment(0)
C
12

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

call_user_func_array('pack', array_merge(array('C*'), $array )))
Cadelle answered 21/8, 2013 at 12:22 Comment(4)
I had seen call_user_func_array() for pack and unpack, but never again remembered it. Thank you.Reine
Can you, please, clarify the solution in terms of unpack function, but not in terms of array_merge?Unamuno
@Unamuno Oh, I see how it works So are you still looking for a new answer, since you put the bounty in or not?Ordain
@ Rizier123. I have to wait 24 hours. before I can accept the answerUnamuno
T
5

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));
Tat answered 12/6, 2015 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.