php字符串与二进制相互转换

源码如下:

// 字符串转换为二进制
// Should output: 0101001101110100011000010110001101101011
$value = unpack(\'H*\', \"Stack\");
echo  _convert($value[1], 16, 2);

// 二进制转换为字符串
// Should output: Stack
echo pack(\'H*\',  _convert(\'0101001101110100011000010110001101101011\', 2, 16));

 

例外一种方法:

<?php
 header(\"Content-type: text/html; charset=utf-8\");
 /**
 * 将字符串转换成二进制
 * @param type $str
 * @return type
 */
 function StrToBin($str){
 //1.列出每个字符
 $arr = preg_split(\'/(?<!^)(?!$)/u\', $str);
 //2.unpack字符
 foreach($arr as &$v){
 $temp = unpack(\'H*\', $v); $v =  _convert($temp[1], 16, 2);
 unset($temp);
 }
 return join(\' \',$arr);
 }
 /**
 * 讲二进制转换成字符串
 * @param type $str
 * @return type
 */
  /* http://www.manongjc.com/article/1587.html */
 function BinToStr($str){
 $arr = explode(\' \', $str);
 foreach($arr as &$v){
 $v = pack(\"H\".strlen( _convert($v, 2, 16)),  _convert($v, 2, 16));
 }
 return join(\'\', $arr);
 }
 echo StrToBin(\"码农教程:www.manongjc.com\");;
 echo \'<br/>\';
 echo BinToStr(\"1110000 1101000 1110000 111001001011101010001100 111001101010110010100001 111001011011110010000000 111001011000111110010001 111011111011110010011010 1110111 1110111 1110111 101110 1110000 1101000 1110000 110010 101110 1100011 1100011\");
收藏 打印