Tuesday, 25 November 2014

Converting a byte value to ascii in 6809

This is less of a tutorial but more a commented snippet of code, When I find more time I will package this up into a zip with some supporting code that will run it on the Vectrex. Please leave any questions, suggestions etc. in the comments or on the vector gaming forum.

Sometimes you want to print a value out in your game, the problem with assembly is that if you decide to print something midway through some other code a you are potentially trashing what you are in the middle of doing.

You could get around this by saving all your registers to the stack, or just print what is in memory later on when it's safe to do so.

First we need a routine to convert our number from binary to decimal.

So in a modern language you might write:

A=123;
print(A);

Output:
123

Easy stuff!

On the Vectrex unless there is a routine already coded to do this in the bios you are going to have to write your own! The first thing we need to think about is what type of decimal value are we going to convert to. A single byte could represent 0 to 255, -128 to 127 or even a fixed point vale. Not to complicate things we are going to write a routine for twos compliment -128 to 127. So here is some commented code that converts whatever is in the A register to ASCII including the sign (+ or -) and a terminator. The terminator tells the Vectrex bios print routine that it should stop printing (otherwise it would keep printing garbage across your screen!).


; Convert 8bit value to ASCII ;Requires 5 bytes of ram to save each digit to ;Debug_0 (sign) ;Debug_1 (Digit 1) ;Debug_2 (Digit 2) ;Debug_3 (Digit 3) ;Debug_4 (string terminator) ;Convert Register A to a 3 byte Decimal for printing to screen Reg_To_Decimal: tfr a,b ;transfer a copy of a to b tstb ;test a to check if neg bpl Reg_DA ;branch if plus (positive) nega ;else is negative so negate a to be positive ldb #45 ;"-" sign stb Debug_0 bra Reg_D0 Reg_DA: ldb #43 ;"+" sign stb Debug_0 Reg_D0: tfr a,b suba #100 bge Reg_D1 ;if 0 or Greater first digit = 1 lda #48 ;else it = 0 = (ascii 48) sta Debug_1 bra Reg_D2 Reg_D1: tfr a,b ;copy remaining number after subtraction of 100 to b lda #49 ;set digit to 1+ascii (ascii 49) sta Debug_1 Reg_D2: clra ;clear a is the counter Reg_D2_Loop: ;Div10 inca ;this might mean our count is 1 more than it should be subb #10 ;take away 10 until it is less than or equal to 0 bge Reg_D2_Loop ;if b is 0 or greater adda #47 ;Result is 1 higher than required so add ascii 48-1 sta Debug_2 ;a count is the middle digit ;b must now contain the final digit but it will be negative, we need to add 10 to b + ascii addb #58 ;add 10+ascii stb Debug_3 lda $80 ;string terminator sta Debug_4 rts

No comments:

Post a Comment