Simple PHP Hack to Print an Integer in Binary Form

Today: Using my own blog as a simple pastebin to remember a helper function I wrote while debugging a good selection of binary operations on integers in PHP. This will simply output the provided value as bit values (0 / 1). Wrap it in <pre>-s if you’re running it in a web context.

$len allows you do change how many bits it will print (starting from lsb – least significant bit), $blockSize adjust the amount of bits before throwing in a space.

function printBinary($val, $len = 32, $blockSize = 8)
{
    print("\n");

    for($i = $len - 1; $i >= 0; $i--)
    {
        print(($val & 0x1<<$i) ? 1 : 0);

        if ($i%$blockSize == 0)
        {
            print (" ");
        }
    }

    print ("\n");
}