开发者

How can I convert array of bytes to a string in PHP?

I have an开发者_运维知识库 array of bytes that I'd like to map to their ASCII equivalents.

How can I do this?


If by array of bytes you mean:

$bytes = array(255, 0, 55, 42, 17,    );

array_map()

Then it's as simple as:

$string = implode(array_map("chr", $bytes));

foreach()

Which is the compact version of:

$string = "";
foreach ($bytes as $chr) {
    $string .= chr($chr);
}
// Might be a bit speedier due to not constructing a temporary array.

pack()

But the most advisable alternative could be to use pack("C*", [$array...]), even though it requires a funky array workaround in PHP to pass the integer list:

$str = call_user_func_array("pack", array_merge(array("C*"), $bytes)));

That construct is also more useful if you might need to switch from bytes C* (for ASCII strings) to words S* (for UCS2) or even have a list of 32bit integers L* (e.g. a UCS4 Unicode string).


Ammending the answer by mario for using pack(): Since PHP 5.5, you can use Argument unpacking via ...

$str = pack('C*', ...$bytes);

The other functions are fine to use, but it is preferred to have readable code.


Yet another way:

$str = vsprintf(str_repeat('%c', count($bytes)), $bytes);

Hurray!


Mario has already provided the best fit, but here is a more exotic way to achieve this.

$str = call_user_func_array(
        'sprintf',
        array_merge((array) str_repeat('%c', count($bytes)), $bytes)
       );

CodePad.


Below is an example of converting Yodlee MFA ByteArray to CAPTCHA image. Hope it helps someone...

You simply have to convert the byte array to string, then encode to base64.

Here is a PHP example:

$byteArray = $obj_response->fieldInfo->image; //Here you get the image from the API getMFAResponse

$string = implode(array_map("chr", $byteArray)); //Convert it to string

$base64 = base64_encode($string); //Encode to base64

$img = "<img src= 'data:image/jpeg;base64, $base64' />"; //Create the image

print($img); //Display the image
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜