Turn decimal into PHP binary

Asked

Viewed 273 times

0

I’m developing an IP calculator in PHP. The problem is that when a mask is typed in decimal, example "255.255.255.0" the mask in binary is displayed " The problem is that doing so, the eight bits of the last Octeto are not displayed, as the last number is "0" in decimal. Below is my code. Does anyone know a way to turn with 32 bits?

 $mascara_decimal = array("", "", "", "");
                $mascara_decimal = explode(".", $_POST["mascara"]);
                $mascara_binario = array("", "", "", "");
                echo "Máscara em decimal: ";
                echo $_POST["mascara"];
                echo"<br>";
                echo "Máscara em binário:&nbsp;";
                for ($i = 0; $i < 4; $i++) {
                    $mascara_binario[$i] = decbin($mascara_decimal[$i]);
                    echo $mascara_binario[$i];
                }

2 answers

1


Use of str_pad:

 for ($i = 0; $i < 4; $i++) {
      $mascara_binario[$i] = str_pad(decbin($mascara_decimal[$i]), 8, "0", STR_PAD_LEFT);
      echo $mascara_binario[$i];
 }

He will fill the missing zeros (0).

1

You can also use the ip2long() to convert to decimal.

Thus:

$decimal = ip2long('255.255.255.0');

Then you can convert from decimal to binary using the decbin and then use the str_pad as using in the @Everson solution. Another option is to simply use the sprintf:

echo sprintf('%032b', ip2long('255.255.255.0'));
// Resultado: 11111111111111111111111100000000

Test this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.