Convert ascii to bcd(binary coded decimal)

Hello everyone

I have a variable $number = 4012;

Is there a way with php to convert this ascii number to a bcd(binary coded decimal)

Thanks in advance,

jmsloan
LVL 3
jmsloanAsked:
Who is Participating?
 
TheClickMasterConnect With a Mentor Commented:


       $number = "1234";
      
       for($i = 0; $i < strlen($number); $i ++)
       {
            $output .= str_pad(decbin($number[$i]), 8, "0", STR_PAD_LEFT)." ";       
       }
      
       echo $output;



Sample output is:

00000001 00000010 00000011 00000100
0
 
venkateshwarrCommented:

If you just want to print a binary number

printf("binary num = %b",$number);
0
 
jmsloanAuthor Commented:
But there is a difference between BCD and a binary number.
0
 
ThGCommented:
TheClickMaster, that's a poor example as it assumes $number is a STRING. Anyway it should work so you can fix it by adding this before "for":

settype($number, 'string');
0
 
ThGCommented:
I HAD to write my own, how beautiful :-)

function dec2bcd($number) {
  $e = 0;
  $ret = 0;
  while ($number) {
    $d = $number % 10;
    $number = floor($number / 10);
    for ($i = 0; $i < $e; $i++) $d <<= 4;
    $ret |= $d;
    $e++;
  }
  return $ret;
}

$dec = 432;
printf("%x\n", dec2bcd($dec));
0
All Courses

From novice to tech pro — start learning today.