We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Convert ascii to bcd(binary coded decimal)

jmsloan
jmsloan asked
on
Medium Priority
4,806 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
Comment
Watch Question


If you just want to print a binary number

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

Author

Commented:
But there is a difference between BCD and a binary number.
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT

Commented:
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');
CERTIFIED EXPERT

Commented:
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));
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.