Author Topic: DEC-to-BCD and BCD-to-DEC conversions  (Read 1074 times)

0 Members and 1 Guest are viewing this topic.

Offline TJ232

  • Frequent Contributor
  • **
  • Posts: 321
  • Country: 00
  • www.esp8266-projects.com
    • ESP8266 Projects
DEC-to-BCD and BCD-to-DEC conversions
« on: February 16, 2017, 03:02:29 pm »
Hi Everybody,

In the process of working on a new Driver Tutorial for the ESPBasic Series I am looking today to implement some Decimal-to-BCD and BCD-to-Decimal subroutines.

What I have done so far:

1. BCD-to-Decimal subroutine:
Code: [Select]
    [DEC]
    hv = val >> 4
    hl = val and 15
    val = hv*10 + hl
    wait 

2. Decimal-to-BCD subroutine:
Code: [Select]
    [BCD]
    d = int( val / 10 )
    d1 = d * 10
    d2 = val - d1
    val = d*16 + d2
    wait

If you have any other idea please feel free to share it, looking forward to see smarter solutions that that. I'm sure they are!

Happy breadboarding,
TJ.

Original Article with Test Program Code: ESPBasic Series - DEC to BCD and BCD to DEC conversions
 

Offline Benta

  • Super Contributor
  • ***
  • Posts: 2199
  • Country: de
Re: DEC-to-BCD and BCD-to-DEC conversions
« Reply #1 on: February 16, 2017, 04:47:52 pm »
It should work, but it's limited to working on only one byte of data.

For arbitrary lengths of digits, setting up a loop using DIV and MOD is somewhat more elegant.

Example for an 8-digit display:

Output is stored in an 8-byte buffer, input is either decimal or binary (use 16 for division instead).

Input value: 12345678. digit_1 is LSD

digit_1 = input MOD(10)  ;(=8)
input = input DIV(10) ;(=1234567)

digit_2 = input MOD(10) ;(=7)
input = input DIV(10) ;(=12345)

and so on. This can be done in a loop with the loop counter used as pointer to the output array. The method can be used for any change of base.

For a single-byte conversion, yours is probably much faster.

 
The following users thanked this post: TJ232

Offline westfw

  • Super Contributor
  • ***
  • Posts: 3145
  • Country: us
Re: DEC-to-BCD and BCD-to-DEC conversions
« Reply #2 on: February 16, 2017, 08:37:22 pm »
There are standard-ish algorithms, mostly encountered in ascii/number conversion:

Code: [Select]
bcdtobin(bcdarray) {
    result = 0;
    while (moredigits(bcdarray)) {
        result = (result * 10) + nextdigit(bcdarray);
    }
    return result;
}

bintobcd(number) {
  reversedbcdarray[] = {0};
  while (number > 0) {
    nextdigit(reversedbcdarray) = number % 10;  // extract the Least significant digit
    number = number / 10;
  }
  return reverse(reversedbcdarray);
}
 
The following users thanked this post: TJ232


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf