PHP中字节/二进制数组的字符串

时间:2009-05-08 15:37:16

标签: php arrays

如何在PHP中将字符串转换为二进制数组?

4 个答案:

答案 0 :(得分:4)

我认为你要求的等同于Perl pack / unpack函数。如果是这种情况,我建议你看一下PHP pack / unpack函数:

答案 1 :(得分:1)

PHP中没有二进制数组这样的东西。所有需要字节流的函数都在字符串上运行你究竟想做什么?

答案 2 :(得分:1)

如果您正在尝试访问字符串的特定部分,则可以像处理数组一样对待它。

$foo = 'bar';
echo $foo[0];

输出:b

答案 3 :(得分:1)

假设您要将$ 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;
?>
相关问题