Turn decimal into PHP binary

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 "1111111111111111111111110" is displayed because I used the function of php DECBIN that transforms decimal into binary. The problem is that by doing this, the eight bits of the last octet are not displayed, since the last number is "0" in decimal. Below is my code. Does anyone know of a way to transform 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];
                }
    
asked by anonymous 04.07.2017 / 23:51

2 answers

1

Use 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];
 }

It will fill in the missing zeros (0).

    
04.07.2017 / 23:59
1

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

This way:

$decimal = ip2long('255.255.255.0');

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

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

Try This

    
05.07.2017 / 03:02