How to use Conversion Algorithm In PHP
We will use the conversion algorithm to convert the Decimal Number to its equivalent Binary Number in PHP. We will define a custom function decimalToBinary that takes a decimal number as input and iteratively divides it by 2, collecting the remainders at each step. Concatenate these remainders in reverse order to get the Binary number. The loop continues until the decimal number becomes zero.
Example:
PHP
<?php // Function to convert Decimanl number to // Binary Number function decimalToBinary( $decNum ) { $binNum = '' ; while ( $decNum > 0) { $rem = $decNum % 2; $binNum = $rem . $binNum ; $decNum = (int)( $decNum / 2); } return $binNum !== '' ? $binNum : '0' ; } $decNum = 25; $binNum = decimalToBinary( $decNum ); echo "Binary Number: " . $binNum ; ?> <?php |
Binary Number: 11001
Decimal to Binary Conversion in PHP
Given a Decimal Number, and the task is to convert a given Decimal Number to a Binary Number using PHP.
Examples:
Input: 10
Output: 1010
Input: 25
Output: 11001
There are different methods to convert the Decimal to a Binary number, these are:
Table of Content
- Using decbin() Function
- Using Conversion Algorithm
- Using Recursion