【发布时间】:2009-05-08 15:37:15
【问题描述】:
如何在 PHP 中将字符串转换为二进制数组?
【问题讨论】:
如何在 PHP 中将字符串转换为二进制数组?
【问题讨论】:
如果您尝试访问字符串的特定部分,您可以将其视为数组。
$foo = 'bar';
echo $foo[0];
输出:b
【讨论】:
在 PHP 中没有二进制数组这样的东西。所有需要字节流的函数都对字符串进行操作。你到底想做什么?
【讨论】:
假设您想将 $stringA="Hello" 转换为二进制。
首先用 ord() 函数取第一个字符。这将为您提供十进制字符的 ASCII 值。在本例中为 72。
现在使用 dec2bin() 函数将其转换为二进制。 然后接下一个函数。 您可以在http://www.php.net 了解这些功能的工作原理。
或者使用这段代码:
<?php
// Call the function like this: asc2bin("text to convert");
function asc2bin($string)
{
$result = '';
$len = strlen($string);
for ($i = 0; $i < $len; $i++)
{
$result .= sprintf("%08b", ord($string{$i}));
}
return $result;
}
// If you want to test it remove the comments
//$test=asc2bin("Hello world");
//echo "Hello world ascii2bin conversion =".$test."<br/>";
//call the function like this: bin2ascii($variableWhoHoldsTheBinary)
function bin2ascii($bin)
{
$result = '';
$len = strlen($bin);
for ($i = 0; $i < $len; $i += 8)
{
$result .= chr(bindec(substr($bin, $i, 8)));
}
return $result;
}
// If you want to test it remove the comments
//$backAgain=bin2ascii($test);
//echo "Back again with bin2ascii() =".$backAgain;
?>
【讨论】: