Hex to ASCII. By Lee Davison. |
The code.I know you've all done this before but here's a use for decimal mode. Read on....
Another way.The classic way to convert a nibble in A into ASCII is to test if the nibble is greater than nine and, if it is, to add seven before adding the 48 to make the ASCII character.
CMP #$0A ; set carry for +1 if >9 BCC NoAdjust ; branch if <=9 ADC #6 ; adjust if A to F ; (six plus carry = 7!) NoAdjust ADC #"0" ; add ASCII "0"This is eight bytes long and takes seven or eight cycles depending on the nibble.
Well here's a way that uses decimal mode addition to do that for you.
SED ; set decimal mode CMP #$0A ; set carry for +1 if >9 ADC #"0" ; add ASCII "0" CLD ; clear decimal modeSix bytes and always nine cycles. Or, if you do a number of nibbles and leave decimal mode set throughout, four bytes and five cycles per digit.
Yet another way.Following some posts on the classiccmp mailing list this became obvious. It's not fast or short (really too long for this section but I'll let it pass) but it doesn't use branches, decimal mode or other registers or memory.
CMP #$0A ; compare the nibble with $0A ADC #$00 ; add 1 if it was >= $0A CMP #$0A ; compare the nibble with $0A ADC #$00 ; add 1 if it was >= $0A CMP #$0A ; compare the nibble with $0A ADC #$00 ; add 1 if it was >= $0A CMP #$0A ; compare the nibble with $0A ADC #$00 ; add 1 if it was >= $0A CMP #$0A ; compare the nibble with $0A ADC #$00 ; add 1 if it was >= $0A CMP #$0A ; compare the nibble with $0A ADC #$00 ; add 1 if it was >= $0A CMP #$0A ; compare the nibble with $0A ADC #"0" ; add "0" and 1 if it was >= $0ATwenty eight bytes and twenty eight cycles, only really usefull for a 'convert hex to ASCII without using branches, decimal mode or look up tables' competition.
Last one, honest. Not the shortest but this must be the fastest way. Starts with the nibble to be converted in X not A
LDA hex_table,X ; get the ASCII character . hex_table .byte "0123456789ABCDEF" ; conversion tableNineteen bytes, eighteen if the table is in page zero, and only four cycles. Speedy!
Last page update: 11th December, 2005. | e-mail me |