Search code examples
phpbitwise-operatorsbit-shift

How to concatenate bits of several bytes in PHP


My self-study in php.net and here has so far not enabled me to find any approach! My experiments with operators like & and >> or << I do not want to show here - too embarrassing!

The starting point are arrays of different lengths with integer values (always 8-bit).

So for instance:

[178, 89, 1]

Their binary coded equivalent...

10110010, 01011001, 00000001 

should be, least significant bit first,...

01001101, 10011010, 10000000

concatenated:

010011011001101010000000

Can someone explain the procedure to me step by step, so that I understand the bit operations in php?

Thank you

Post scriptum: I don't want to solve the problem with string operations (I can do that - but it's terribly slow!), but with bit operations.


Solution

  • probably you need something like this:

    <?php
    $array = [178, 89, 1];
    
    $output = 0;
    foreach ($array as $v) {
        for ($i = 0; $i < 8; $i++) {
            $output = ($output << 1) | ($v & 1);
            $v = $v >> 1;
        }
    }
    
    echo $output . " " . str_pad(decbin($output), 24, 0, STR_PAD_LEFT);
    

    now step by step:

    1. for every element in input array we're getting 0th bit (less significant) - $v & 1
    2. output variable is shifted left to provide space for this bit $output << 1
    3. bit is set to the most right position in output variable | part
    4. we shift variable to the right, so 1st bit becomes 0th
    5. repeat for the rest