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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:02:25  来源:igfitidea点击:

String to byte/binary arrays in PHP

phparrays

提问by Jeff Winkworth

How do I convert a string to a binary array in PHP?

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

采纳答案by earino

I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions:

我认为您要求等效于 Perl 打包/解包功能。如果是这种情况,我建议您查看 PHP 打包/解包函数:

回答by hdaf

Let's say that you want to convert $stringA="Hello" to binary.

假设您想将 $stringA="Hello" 转换为二进制。

First take the first character with ord() function. This will give you the ASCII value of the character which is decimal. In this case it is 72.

首先用 ord() 函数取第一个字符。这将为您提供十进制字符的 ASCII 值。在这种情况下,它是 72。

Now convert it to binary with the dec2bin() function. Then take the next function. You can find how these functions work at http://www.php.net.

现在使用 dec2bin() 函数将其转换为二进制。然后执行下一个函数。您可以在http://www.php.net 上找到这些函数的工作原理。

OR use this piece of code:

或使用这段代码:

<?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;
?>

回答by soulmerge

There is no such thing as a binary array in PHP. All functions requiring byte streams operate on strings. What is it exactly that you want to do?

PHP 中没有二进制数组这样的东西。所有需要字节流的函数都对字符串进行操作。你到底想要做什么?

回答by McAden

If you're trying to access a specific part of a string you can treat it like an array as-is.

如果您尝试访问字符串的特定部分,您可以将其视为数组。

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

output: b

输出:b