0

我知道这种接缝很容易,但是我对这种特殊情况有疑问。我已经知道如何使用 PHP 将十进制转换为二进制,但我想显示完整的位序列,但令人惊讶的是,我不知道如何。

转换必须是这样的:

converting 127(decimal) to binary using PHP = 1111111. the bit sequence is 1-128 for every 
octet(IP Address) so this must output = 01111111 even 128 is not used.
2nd Example:
1(decimal) to binary = 01. Want to display the full 1-128 binary sequence even if
128,64,32,16,8,4,2 is not used it must be like this 00000001 not 01.

这是我的 PHP 代码:

<?php

        $octet1 = $_POST["oct1"];
        $octet2 = $_POST["oct2"];
        $octet3 = $_POST["oct3"];
        $octet4 = $_POST["oct4"];
        echo decbin($octet1) ," ", decbin($octet2) ," ", decbin($octet3) ," ", decbin($octet4);

    ?>

这只显示缩短的二进制文件,如下所示:

16 to binary is 10000 or but i want to display this 00010000(Full length)

我怎样才能做到这一点?

4

2 回答 2

5

如何使用sprintf格式b说明符:

echo sprintf("%08b", 127);
// 01111111
echo sprintf("%08b.%08b.%08b.%08b", 127, 0, 0, 1);
// 01111111.00000000.00000000.00000001
于 2013-01-24T10:33:52.153 回答
1

你需要填充它:

echo str_pad($str, 8, '0', STR_PAD_LEFT);
于 2013-01-24T10:31:13.530 回答