我知道这种接缝很容易,但我对这种特殊情况有疑问。 我已经知道如何使用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)
我该怎么做?
答案 0 :(得分:5)
如何将sprintf
与 b
格式说明符一起使用:
echo sprintf("%08b", 127);
// 01111111
echo sprintf("%08b.%08b.%08b.%08b", 127, 0, 0, 1);
// 01111111.00000000.00000000.00000001
答案 1 :(得分:1)
你需要填充它:
echo str_pad($str, 8, '0', STR_PAD_LEFT);