如何在 PHP 中连接多个字节

我在php.net和这里的自学到目前为止还没有让我找到任何方法!我不想在这里展示我对像&and >>or 这样的运算符的实验- 太尴尬了!<<

起点是具有整数值(始终为 8 位)的不同长度的数组。

例如:

[178, 89, 1]

它们的二进制编码等效...

10110010, 01011001, 00000001

应该是,最低有效位在前,...

01001101, 10011010, 10000000

连接:

010011011001101010000000

有人可以一步步向我解释该过程,以便我理解php中的位操作吗?

谢谢

后记:我不想用字符串操作来解决问题(我可以这样做 - 但它非常慢!),而是用位操作来解决。


互换的青春
浏览 70回答 3
3回答

撒科打诨

使用decbin()但你需要0向左填充,否则00000001会1再次变成。一种方法是使用array_reduce(),尽管您可以通过多种方式循环数组。<?php$array = [178, 89, 1];echo array_reduce($array, function ($acc, $byte) {   return $acc.strrev(str_pad(decbin($byte), 8, 0, STR_PAD_LEFT));})结果:010011011001101010000000https://3v4l.org/D4qGr

陪伴而非守候

也许你需要这样的东西:<?php$array = [178, 89, 1];$output = 0;foreach ($array as $v) {&nbsp; &nbsp; for ($i = 0; $i < 8; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $output = ($output << 1) | ($v & 1);&nbsp; &nbsp; &nbsp; &nbsp; $v = $v >> 1;&nbsp; &nbsp; }}echo $output . " " . str_pad(decbin($output), 24, 0, STR_PAD_LEFT);现在一步一步:对于输入数组中的每个元素,我们得到第 0 位(不太重要)-$v & 1输出变量左移以为该位提供空间$output << 1|位被设置到输出变量部分的最右边的位置我们将变量向右移动,因此第 1 位变为 0重复其余部分

翻阅古今

<?phpfunction dec2bin_i($decimal_i){&nbsp;bcscale(0);&nbsp;$binary_i = '';&nbsp;do&nbsp; {&nbsp; &nbsp;$binary_i = bcmod($decimal_i,'2') . $binary_i;&nbsp; &nbsp;$decimal_i = bcdiv($decimal_i,'2');&nbsp; } while (bccomp($decimal_i,'0'));&nbsp;return($binary_i);}//empty output string$output = '';//define array$array = [178, 89, 1];//loop array valuesforeach($array as $value){&nbsp; &nbsp; //convert to binary and concatenate&nbsp; &nbsp; $output .= dec2bin_i($value);}//show outputecho $output;?>
打开App,查看更多内容
随时随地看视频慕课网APP