Jump to content
  • entries
    17
  • comments
    28
  • views
    32,280

Hex to BCD conversion (0-99)


Omegamatrix

2,864 views

I can't sleep. I'm consumed by this problem and I keep thinking about it...

 

Tonight I discovered some of Batari's solutions for hex to bcd conversion here and here. They are very compact solutions, and neat. I started to wonder if a constant (un-looped) cycle approach could be found without using tables. Then the insomnia crept in. :) I decided to have a go at translating hex values of 0-99 (BCD range for a byte).

 

The approach I took was to modify my divide by 10 routine so that the result was multiplied by 6, and then added it to the initial value. From there I optimized it so that some of the shifts could be cut out, and removed the correction value (adc #13) from the divide routine, because that is only required for values 130 or more (and we are just doing 0-99).

 

Here is what I came up with:

;Hex2Bcd (good 0-99)
;24 bytes, 39 cycles
;You can also use LSR for all ROR's here...

  sta  temp
  lsr
  adc  temp
  ror
  lsr
  lsr
  adc  temp
  ror
  adc  temp
  ror
  lsr
  and  #$3C
  sta  temp2
  lsr
  adc  temp2
  adc  temp
 

I wrote a real short verification program. Basically just a macro that pumps out all the results and stuffs them into zero page ram, which can easily been seen in Stella's debugger. I did a visual verification.

blogentry-7074-0-14972200-1393321956_thumb.png

 

hex2bcd.zip

 

 

  • Like 4

3 Comments


Recommended Comments

Very nice! It's one of those routines that looks like magic if there isn't an explanation.

 

Do you mind if I add it as a utility function to 7800basic?

Link to comment

Yeah, absolutely go ahead. :) The caveat is that it does no checking for numbers 100-255, so it is up to the user to ensure the starting number is 0-99.

  • Like 1
Link to comment

Thanks!

 

Understood about the lack of range check. I'll document that and leave it up to the end-user. That way the routine can stay nice and lean.

Link to comment
Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...