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\"); 继续阅读与本文标签相同的文章
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
-
量子信息和量子技术白皮书合肥宣言在中科大发布
2026-05-14栏目: 教程
-
微信悄悄更新一新功能,来看看!
2026-05-14栏目: 教程
-
打破三大运营商垄断,第四大运营商终于来了!
2026-05-14栏目: 教程
-
梦幻西游:武神坛参赛队伍暴增几倍,一下就回到了曾经的巅峰时期
2026-05-14栏目: 教程
