[英]PHP Convert Byte to byte array
My code receive some json with a byte field like 48656C6C6F
,and I'm trying to convert it to a byte pairs in array like array[0] = 48, array[1]=65 ...
in order to work with each byte.我的代码接收一些带有像
48656C6C6F
这样的字节字段的 json,我试图将它转换为像array[0] = 48, array[1]=65 ...
这样的array[0] = 48, array[1]=65 ...
的字节对array[0] = 48, array[1]=65 ...
以便处理每个字节.
Actually, I've made this bypass function in order to have the array:实际上,我已经制作了这个绕过功能,以便拥有数组:
function Array_conv($hex){
$chunks = str_split($hex, 2);
$result = implode(',', $chunks);
return $result;
}
The question is, have a right way to convert to a byte array, or to hex like 0x48..问题是,有一个正确的方法来转换为字节数组,或像 0x48..
Thanks!谢谢!
Strings in PHP are just as well suited to access every single byte as arrays. PHP 中的字符串与数组一样适合访问每个字节。
$hex = "48656C6C6F";
$string = hex2bin($hex);
var_dump($string); //string(5) "Hello"
The function strlen() returns the length in Byte.函数 strlen() 以字节为单位返回长度。 With a simple for loop you can get every Byte.
通过一个简单的 for 循环,您可以获得每个字节。 With ord() you get the byte as an unsigned integer between 0 and 255.
使用 ord() 可以将字节作为 0 到 255 之间的无符号整数。
$byteLen = strlen($string);
for($i=0; $i < $byteLen; $i++){
$byte = $string[$i];
echo ord($byte).",";
}
Output:输出:
72,101,108,108,111,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.