Home > Article > Backend Development > 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.列出每个字符 // 这边的分割正则也不理解 // (?'; 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!