PHP How to Convert Decimal to Binary with Example
In PHP, you can convert a decimal number to binary using the built-in function
decbin(), for example, decbin(10) returns 1010.Examples
Input10
Output1010
Input0
Output0
Input255
Output11111111
How to Think About It
To convert a decimal number to binary, think about dividing the number by 2 repeatedly and recording the remainder each time. These remainders, read in reverse order, form the binary number. PHP's
decbin() function does this automatically for you.Algorithm
1
Get the decimal number as input.2
Use the built-in function to convert it to binary.3
Return or print the binary string.Code
php
<?php $decimal = 10; $binary = decbin($decimal); echo "Binary of $decimal is $binary"; ?>
Output
Binary of 10 is 1010
Dry Run
Let's trace the conversion of decimal 10 to binary using decbin()
1
Input decimal number
decimal = 10
2
Call decbin function
binary = decbin(10) // returns '1010'
3
Output binary string
Print 'Binary of 10 is 1010'
| Decimal | Binary |
|---|---|
| 10 | 1010 |
Why This Works
Step 1: Using decbin()
The decbin() function converts a decimal number to its binary string representation automatically.
Step 2: Input and output
You provide the decimal number as input, and it returns a string of 0s and 1s representing the binary form.
Step 3: Printing result
You can print or use the binary string as needed in your program.
Alternative Approaches
Manual division method
php
<?php function decimalToBinary($decimal) { $binary = ''; if ($decimal == 0) return '0'; while ($decimal > 0) { $binary = ($decimal % 2) . $binary; $decimal = intdiv($decimal, 2); } return $binary; } echo decimalToBinary(10); // outputs 1010 ?>
This method shows the logic behind conversion but is longer and less efficient than using decbin().
Complexity: O(log n) time, O(log n) space
Time Complexity
The conversion depends on the number of bits in the decimal number, which is proportional to log base 2 of the number.
Space Complexity
The output string length grows with the number of bits, so space is also proportional to log base 2 of the input.
Which Approach is Fastest?
Using the built-in decbin() is fastest and most optimized compared to manual methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| decbin() built-in | O(log n) | O(log n) | Quick and easy conversion |
| Manual division | O(log n) | O(log n) | Learning and understanding logic |
Use PHP's built-in
decbin() function for quick and reliable decimal to binary conversion.Beginners often forget that
decbin() returns a string, not a number, so treat the result accordingly.