Home >Backend Development >PHP Problem >How to convert php to binary
How to convert php to binary: first create a PHP sample file; then define a StrToBin method; then parse the string through the unpack method; and finally convert to binary through the "base_convert" function.
Recommended: "PHP Video Tutorial"
PHP String to Binary Conversion
I found a method for converting string to binary on the Internet (the relevant problem description and problems are in the following code, please read it patiently, thank you):
/** * 将字符串转换成二进制 * @param type $str * @return type * php 中显示的字符串是多少进制的?? * 例如:$str = '你好'; // 这边的 '你好' 是什么进制数据(我知道他是字符串!)?? */ function StrToBin($str){ //1.列出每个字符 // 这边的分割正则也不理解 // (?<!^) 后瞻消极断言 // (?!$) 前瞻消极断言 // 看意思好像说的是:不以^开头(但是这边 ^ 又没有被转义...),不以 $ 结尾(同上) // 然后得到的记过就是字符串一个个被分割成了数组(郁闷) // 求解释 $arr = preg_split('/(?<!^)(?!$)/u', $str); //2.unpack字符 foreach($arr as &$v){ /** * unpack:将二进制字符串解包(英语原文:Unpack data from binary string) * H: 英语描述原文:Hex string, high nibble first * 这段代码做了什么?? */ $temp = unpack('H*', $v); // 这边被解析出来的字符串为什么是 16进制的?? $v = base_convert($temp[1], 16, 2); unset($temp); } return join(' ',$arr); } /** * 讲二进制转换成字符串 * @param type $str * @return type */ function BinToStr($str){ $arr = explode(' ', $str); foreach($arr as &$v){ // 他做了什么?? $v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16)); } return join('', $arr); } echo StrToBin("php二次开发:www.php2.cc");; echo '<br/>'; echo BinToStr("1110000 1101000 1110000 111001001011101010001100 111001101010110010100001 111001011011110010000000 111001011000111110010001 111011111011110010011010 1110111 1110111 1110111 101110 1110000 1101000 1110000 110010 101110 1100011 1100011");
How do the above functions realize conversion between binary and string? ?
-------Separator-------
I already know about pack and unpack! By the way, let me share:
Let’s use this example to talk about what I understand:
pack usage:
// 二进制数字 => 二进制字符串 $bin_number = '这边是二进制数字'; $hex = bin2hex($bin_number ); // 由于指定了 H(16进制,高位在前),所以第二个参数需要使 16 进制字字符串 // strlen($hex) 指定打包多少个 16 进制字符串 // 也可以使用 * 来自动识别 // 结果就是:二进制字符串了 $bin_str = pack('H' . strlen($hex) , $hex); <=> $dec = bindec($bin_number); $hex = dechex($dec); $bin_str = hex2bin($hex); unpack 用法: // 转换作用:2进制字符串 => 16进制字符串 $str = unpack('H*' , '陈'); <=> $str = bin2hex('陈');
The above is the detailed content of How to convert php to binary. For more information, please follow other related articles on the PHP Chinese website!