Reputation: 693
I know this seams to be easy but, I have a question to this particular situation. I already know how to convert decimal to binary using PHP, but I want to display the full bit sequence, but surprisingly, I don't know how.
the conversion must be like this:
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.
this is my PHP code:
<?php
$octet1 = $_POST["oct1"];
$octet2 = $_POST["oct2"];
$octet3 = $_POST["oct3"];
$octet4 = $_POST["oct4"];
echo decbin($octet1) ," ", decbin($octet2) ," ", decbin($octet3) ," ", decbin($octet4);
?>
this only displays the shortened binary just like this:
16 to binary is 10000 or but i want to display this 00010000(Full length)
How can I do that?
Upvotes: 0
Views: 1453
Reputation: 272106
How about using sprintf
with b
format specifier:
echo sprintf("%08b", 127);
// 01111111
echo sprintf("%08b.%08b.%08b.%08b", 127, 0, 0, 1);
// 01111111.00000000.00000000.00000001
Upvotes: 5