问题描述
我有一个字节数组,我想映射到它们的ASCII等效项.
I have an array of bytes that I'd like to map to their ASCII equivalents.
我该怎么做?
推荐答案
如果按字节数组表示,则表示:
If by array of bytes you mean:
$bytes = array(255, 0, 55, 42, 17, );
array_map()
那么就这么简单:
array_map()
Then it's as simple as:
$string = implode(array_map("chr", $bytes));
foreach()
哪个是以下版本的精简版本:
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()
但最可取的选择是使用pack("C*", [$array...])
,即使它需要PHP中的时髦数组变通方法来传递整数列表:
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)));
如果您可能需要从字节 C * (对于ASCII字符串)切换到单词 S * (对于UCS2),或者甚至具有一个 L * 的32位整数列表(例如UCS4 Unicode字符串).
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).
这篇关于如何在PHP中将字节数组转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!