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