Open In App

Convert Number to Binary Coded Decimal in PHP

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




<?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:

  • The decimalToBCD( ) function takes a decimal number as input.
  • It extracts each digit of the number using the modulo operator `%` and converts it to a 4-bit binary string using decbin( ).
  • The str_pad( ) function is used to ensure that each binary representation is 4 characters long by padding with zeros on the left if necessary.
  • The binary strings are concatenated to form the BCD representation.
  • The loop continues until all digits of the number have been processed.

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




<?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:

  • The str_split() function is used to split the number into an array of its digits.
  • The array_map( ) function applies a callback function to each digit, converting it to a 4-bit binary string.
  • The implode function( ) joins the binary strings to form the BCD representation.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads