当前位置:网站首页>PHP string to binary conversion

PHP string to binary conversion

2022-07-01 09:42:00 Squatting in the corner counting ants

1、 Description of related functions

        pack: Load data into a binary string

        unpack: Unpacking data from binary strings

        preg_split : Separate strings with a regular expression .

        explode: Break a string into an array

        join: Combine array elements into a string

2、 Example

2.1 Convert a string to binary

/** 
*  Convert a string to binary  
* @param type $str 
* @return type 
*/ 
function StrToBin($str){  
    //  The segmentation rules here don't understand , Why is the rule like this 
    $arr = preg_split('/(?<!^)(?!$)/u', $str);  
    //2.unpack character   
    foreach($arr as &$v){
        //unpack: Unpack binary strings 
        //H: Hexadecimal string , High in the former , And pack bring into correspondence with , You can also use  *  To automatically identify 
        $temp = unpack('H*', $v); 
        $v = base_convert($temp[1], 16, 2);  
        unset($temp);  
    }  
    return join(' ',$arr);  
}  

  

  2.2 Convert binary to string  

/**
*  Convert binary to string  
* @param type $str 
* @return type 
*/ 
function BinToStr($str){  
    $arr = explode(' ', $str);  
    foreach($arr as &$v){  
        // Load data into a binary string 
        //strlen()  Specify how many  16  Base string 
        // Because of the designation  H(16 Base number , High in the former ), So the second parameter needs to make  16  Hexadecimal character string 
        $v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));  
    }  
    return join('', $arr);  
}  

2.3 Test examples


// test 
echo StrToBin("php Binary test ");;  
echo '<br/>';  
echo BinToStr("1110000 1101000 1110000 111010001011111110011011 111001011000100010110110 111001101011010110001011 111010001010111110010101");

原网站

版权声明
本文为[Squatting in the corner counting ants]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010937244999.html