<?Php
echo decbin(3); // Output 11
echo "<br>";
echo decbin(35); // Output 100011
echo "<br>";
echo decbin(100); // Output is 1100100
echo "<br>";
echo decbin(258); // Output is 100000010
echo "<br>";
echo decbin(1000); // Output is 1111101000
echo "<br>";
?>
Syntax
string decbin(int $number);
Parameter | DESCRIPTION |
$number | Required : Decimal number as Input to convert to equivalent binary number. |
The output is string converted to binary base system.
Example 1: Converting Negative Numbers to Binary
<?php
echo decbin(-5); // Output: '-101' (Two's complement is not handled by decbin)
?>
Example 2: Converting Large Decimal Numbers to Binary
<?php
echo decbin(9999999); // Output: 100110001001011001111111
?>
Example 3: Using Binary Numbers for Bitwise Operations
<?php
$a = 5; // 101 in binary
$b = 3; // 11 in binary
echo decbin($a & $b); // Output: 1 (bitwise AND)
?>
Example 4: Padding Binary Numbers with Leading Zeros
<?php
$number = 7;
echo str_pad(decbin($number), 8, '0', STR_PAD_LEFT); // Output: 00000111
?>
Example 5: Converting Multiple Decimal Numbers in a Loop
<?php
$numbers = [2, 4, 8, 16];
foreach ($numbers as $num) {
echo "Decimal: $num => Binary: " . decbin($num) . "<br>";
}
?>
Example 6: Converting Decimal to Binary and Back to Decimal
<?php
$decimal = 25;
$binary = decbin($decimal);
echo "Binary: $binary <br>";
echo "Back to Decimal: " . bindec($binary); // Output: 25
?>
Example 7: Handling Binary with Different Lengths
<?php
$decimal1 = 5; // 101 in binary
$decimal2 = 32; // 100000 in binary
echo str_pad(decbin($decimal1), 6, '0', STR_PAD_LEFT); // Output: 000101
echo "<br>";
echo str_pad(decbin($decimal2), 6, '0', STR_PAD_LEFT); // Output: 100000
?>
← Math Functions
base_convert(): Convert number From any base to other →
bindec(): Decimal equivalent of Binary string →
← Subscribe to our YouTube Channel here