简体   繁体   English

如何在PHP中将十六进制数据表示转换为二进制数据?

[英]How to convert hexadecimal representation of data to binary data in PHP?

I'm familiar with php's function bin2hex() for converting binary data to its hexadecimal representation. 我熟悉php的函数bin2hex()用于将二进制数据转换为十六进制表示。

However, what is the complement function to convert the hexadecimal representation of the data back to binary data? 但是,将数据的十六进制表示转换回二进制数据的补码函数是什么?

For example: 例如:

$foo = "hello";
$foo = bin2hex($foo);
echo $foo; // Displays 68656c6c6f

How do I turn it back to "hello"? 我怎么把它变回“你好”?

$foo = "68656c6c6f";
// Now what?

There is no hex2bin() function. 没有hex2bin()函数。

If you look at PHP's bin2hex page , there's suggested solutions including this one: 如果你看看PHP的bin2hex页面 ,建议的解决方案包括这个:

$foo = pack("H*" , $foo);
echo $foo;

There's also various implementations of hex2bin that you can choose from. 您还可以选择各种hex2bin实现。

For those who have PHP 5.4 and above, there's a standard way of doing this: 对于那些拥有PHP 5.4及以上版本的用户,有一种标准的方法:

<?php $bin = hex2bin("6578616d706c65206865782064617461"); var_dump($bin); ?>

The output of the code above should be similar to: 上面代码的输出应类似于:

string(16) "example hex data"

Gotten off of the PHP hex2bin page . 脱掉了PHP hex2bin页面

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

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