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 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.

Table of Content

  • Using String Manipulation
  • Using Array Operations

Similar Reads

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....

Convert Number to Binary Coded Decimal using Array Operations

...

Contact Us