我有一个字节数组,想将其映射到对应的ASCII码。
我应该怎么做?
如果您所说的“字节数组”是指:
$bytes = array(255, 0, 55, 42, 17, );
那么它就像这样简单:
$string = implode(array_map("chr", $bytes));
这是以下代码的简化版:
$string = "";
foreach ($bytes as $chr) {
$string .= chr($chr);
}
// Might be a bit speedier due to not constructing a temporary array.
然而,最可取的替代方案可能是使用pack("C*", [$array...])
,尽管它需要在PHP中使用一些奇特的数组解决方法来传递整数列表:
$str = call_user_func_array("pack", array_merge(array("C*"), $bytes)));
如果你需要从字节C*(用于ASCII字符串)切换到单词S*(用于UCS2)甚至是32位整数列表L*(例如UCS4 Unicode字符串),那么这种构造也更有用。
针对使用pack()
的回答,根据mario的建议进行修正:
自PHP 5.5以来,您可以通过...
使用参数解包。
$str = pack('C*', ...$bytes);
其他函数可以使用,但最好编写可读性强的代码。
$str = vsprintf(str_repeat('%c', count($bytes)), $bytes);
万岁!
$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