Solved

Convert ascii to bcd(binary coded decimal)

Posted on 2004-04-12
5
4,274 Views
Last Modified: 2007-12-19
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
Comment
Question by:jmsloan
5 Comments
 
LVL 12

Expert Comment

by:venkateshwarr
ID: 10805218

If you just want to print a binary number

printf("binary num = %b",$number);
0
 
LVL 3

Author Comment

by:jmsloan
ID: 10805621
But there is a difference between BCD and a binary number.
0
 
LVL 5

Accepted Solution

by:
TheClickMaster earned 50 total points
ID: 10807227


       $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
 
LVL 14

Expert Comment

by:ThG
ID: 10812211
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
 
LVL 14

Expert Comment

by:ThG
ID: 10812254
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

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question