简体   繁体   English

将二进制数据转换为PHP中的十六进制字符串

[英]Binary data to hex string in PHP

I need to take some binary data and convert it to hex. 我需要获取一些二进制数据并将其转换为十六进制。 When I do 当我做

$value = bin2hex($msg);

$value is "0003". $ value是“ 0003”。 However I need it to be a hex string, like 0x0003 or even just "03" (hex), in order to use it. 但是我需要它是一个十六进制字符串,例如0x0003或什至只是“ 03”(十六进制)才能使用它。

How can I convert it? 如何转换?

I thing you need to convert a string to hex string to use bin2hex($msg); 我需要将字符串转换为十六进制字符串才能使用bin2hex($msg); You can use this 你可以用这个

function strToHex($string){
$hex = '';
for ($i=0; $i<strlen($string); $i++){
    $ord = ord($string[$i]);
    $hexCode = dechex($ord);
    $hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);}

Like This 像这样

 $value = bin2hex(strToHex($msg));

Give it a try 试试看

  $value = dechex(bindec($msg));
     echo $value ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM