Solved

Convert ascii to bcd(binary coded decimal)

Posted on 2004-04-12
5
4,264 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

744 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now