Open In App

Convert Number to Binary Coded Decimal in PHP

Binary Coded Decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of binary digits, usually four or eight. This article will explore how to convert a decimal number to its BCD representation in PHP with multiple approaches.

Convert Number to Binary Coded Decimal using Modulus and Division Approach

In PHP, you can convert a number to Binary Coded Decimal (BCD) using string manipulation by first converting the number to a string, then splitting the string into individual digits, and finally converting each digit to its corresponding 4-bit binary representation.

Example: Implementation to convert numbers to binary coded decimal.






<?php
  
function decimalToBCD($number) {
    $bcd = "";
  
    while ($number > 0) {
        $digit = $number % 10;
  
        $bcd = str_pad(decbin($digit), 4, "0", STR_PAD_LEFT) . $bcd;
  
        $number = (int) ($number / 10);
    }
    return $bcd;
}
  
// Driver code
$number = 123;
  
$bcd = decimalToBCD($number);
echo "BCD of $number is $bcd";
  
?>

Output
BCD of 123 is 000100100011

Explanation:

Convert Number to Binary Coded Decimal using Array Operations

In PHP, you can convert a number to Binary Coded Decimal (BCD) using array operations by first splitting the number into individual digits using str_split( ), then mapping each digit to its 4-bit binary representation using array_map( ), and finally joining the binary representations together using implode( ).

Example: Implementation to convert numbers to binary coded decimal.




<?php
  
function decimalToBCD($number) {
    $digits = str_split($number);
  
    $bcdArray = array_map(function ($digit) {
        return str_pad(decbin($digit), 4, "0", STR_PAD_LEFT);
    }, $digits);
  
    return implode("", $bcdArray);
}
  
// Driver code
$number = 123;
  
$bcd = decimalToBCD($number);
echo "BCD of $number is $bcd";
  
?>

Output
BCD of 123 is 000100100011

Explanation:


Article Tags :