php字符串和2进制互相转换

第一种:
function strtobin($str){
    //1.列出每个字符
    $arr = preg_split('/(?<!^)(?!$)/u', $str);
    //2.unpack字符
    foreach($arr as &$v){
        $temp = unpack('H*', $v);
        $v = base_convert($temp[1], 16, 2);
        unset($temp);
    }

    return join(' ',$arr);
}

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 bintostr(strtobin('hello, 你好啊!'));
第二种方法:
function str2bin($str = ''){
    $bin_arr = array();
    $str_arr = preg_split('//u', $str, 0, PREG_SPLIT_NO_EMPTY);
    foreach ($str_arr as $val) {
        if (ord($val) > 127) {
            $bin_arr[] = base_convert(str_replace('%', '', urlencode($val)), 16, 2);
        } else {
            $bin_arr[] = decbin(ord($val));
        }
    }
    return implode(' ', $bin_arr);
}

function bin2str($bin_str = ''){
    $str = '';
    $bin_str = explode(' ', $bin_str);
    foreach ($bin_str as $val) {
        if (bindec($val) < 127) {
            $str .= chr(bindec($val));
        } else {
            $str .= urldecode('%' . implode('%', str_split(base_convert($val, 2, 16), 2)));
        }
    }
    return $str;
}
echo bin2str(str2bin('hello, 你好啊!'));

你可能感兴趣的:(2进制转字符串,字符串转2进制)