Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4500
  • Last Modified:

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
0
jmsloan
Asked:
jmsloan
1 Solution
 
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
 
TheClickMasterCommented:


       $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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now