Conversion of four-digit hex to ASCII in 8051


We have already seen how to convert Hexadecimal digit to its ASCII equivalent. In this section, we will see how to convert two-byte (4-digit) Hexadecimal number to ASCII. Each nibble of these numbers is converted to its ASCII value.

We are using one subroutine to convert a hexadecimal digit to ASCII. In this program, we are calling the subroutine multiple times.

In the memory, we are storing 2-byte Hexadecimal number at location 20H and 21H. After converted ASCII values are stored at location 30H to 33H.

The hexadecimal number is 2FA9H. The ASCII equivalent is 32 46 41 39.

Address
Value


.
.
.
20H
2FH
21H
A9H


.
.
.
30H
00H
31H
00H
32H
00H
33H
00H


.
.
.


Program

        MOVR0,#20H;set source address 20H to R0
        MOVR1,#30H;Set destination address 30H to R1
        MOVR5,#02H;Set the counter as 2 for 2-bytes

LOOP:   MOVA,@R0; Get the first byte from location 20H
        MOVR4,A; Store the content of A to R4
        SWAPA; Swap Nibbles of A
        ANLA,#0FH; Mask upper nibble of A
        ACALL HEX2ASC; Call subroutine to convert HEX to ASCII
        MOV@R1,B; Store the ASCII to destination
        INCR1; Increment the dest address

        MOVA,R4; Take the original number again
        ANLA,#0FH; Mask upper nibble of A
        ACALL HEX2ASC ; Call subroutine to convert HEX to ASCII
        MOV@R1,B; Store the ASCII to destination
        INCR1; Increment the destination address

        INCR0; Increase R0 for next source address
        DJNZR5,LOOP ; Decrease the byte count, and iterate
HALT:   SJMP HALT ;Stop the program
;This is a subroutine to convert Hex to ASCII. It takes A and B registers. A is holding the input, and B is for output

HEX2ASC:    MOVR2,A; Store the content of A into R2

CLRC;Clear the Carry Flag
SUBBA,#0AH;Subtract 0AH from A
JCNUM ;When carry is present, A is numeric
ADDA,#41H;Add41H for Alphabet
SJMP STORE ;Jumpto store the value
NUM: MOVA,R2;Copy R2 to A
ADDA,#30H;Add 30H with A to get ASCII
STORE: MOVB,A;Store A content to B
RET

In this program, we are taking the number into the accumulator. Then to get the hexadecimal digits individually, we will apply masking logic. 

Here the HEX2 ASC subroutine is using the register A and B. A is acting like the input argument and B as output. 

Output

Address
Value


.
.
.
20H
2FH
21H
A9H


.
.
.
30H
32H
31H
46H
32H
41H
33H
39H


.
.
.

Updated on: 27-Jun-2020

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements