Search code examples
phparraysbytebit

PHP Convert a dec to a bit array with a predefined length


I'm getting confused on how to do a simple thing, perhaps someone can help me.

At one point of my code I convert a bit array with 10 alarms (0 or 1) to a decimal and save it. At another point I load the decimal and want to convert it back to a bit array.

This works however the bit array should be always have a length of 10 even if the decimal length is not 10 bites.

See my code:

// Convert array to dec:
$alarms = array(0,0,1,0,0,0,1,0,0,0);
$str = implode("", $alarms);
$dec = bindec($str);

// Convert back to bit array:
$bin = decbin($dec);

echo $bin;

The result of this code is:

10001000

But should be:

0010001000

Thanks!


Solution

  • Here's an idea of how you might implement this.

    <?php
    
    // Input array of bits
    $inBits = [0,0,1,0,0,0,1,0,0,0];
    // Convert to decimal value
    $value = bindec(implode('', $inBits));
    // Convert back to string of 0/1, adding padding as needed.
    $outBitStr = str_pad(decbin($value), count($inBits), '0', STR_PAD_LEFT);
    
    var_dump(implode('', $inBits) === $outBitStr); // TRUE