Registers are easiest to read in hexadecimal: one hex digit is 4 bits, so a byte is two digits. The code of the letter A is 41h, written 41.
What to build
Read one key and print the code of the key as two hexadecimal digits, with capital letters.
Requirements
- Split the byte in the top 4 bits and the bottom 4 bits.
- Convert each half, a number from 0 to 15, into a character:
0to9, thenAtoF. - Print the high digit first.
Input
One character, then Enter.
Output
Two hex digits, for example 41 for A and 7A for z.
Constraints
The characters printed have to be ASCII characters in the range 20h to 7Eh.
Example
Input:
A
Output:
41
Why it works
Shifting right by 4 moves the top half of the byte down so it can be read as a number from 0 to 15, and AND with 0Fh keeps only the bottom half. A number from 10 to 15 must become A to F, which are 7 characters after 9 in the ASCII table, so 7 is added for them on top of the 30h that every digit needs.
Examples
A
41
z
7A
Hints
Hint 1
Keep the key in BL. The high hex digit is the top 4 bits: copy BL to DL, then MOV CL, 4 and SHR DL, CL.
Hint 2
The low hex digit is the bottom 4 bits: copy BL to DL and AND DL, 0FH.
Hint 3
Turn a value from 0 to 15 into a character: add '0'; if the value is above 9, also add 7 (so that 10 becomes 'A'). Use CMP DL, 9 and JBE.
Solution
Show one correct solution (try it yourself first)
; The hex code of a key
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
MOV AH, 1
INT 21H
MOV BL, AL
MOV DL, BL
MOV CL, 4
SHR DL, CL ; the high half
CALL SHOWHEX
MOV DL, BL
AND DL, 0FH ; the low half
CALL SHOWHEX
MOV AH, 4CH
INT 21H
MAIN ENDP
SHOWHEX PROC ; prints DL (0 to 15) as a hex digit
CMP DL, 9
JBE DIGIT
ADD DL, 7
DIGIT:
ADD DL, '0'
MOV AH, 2
INT 21H
RET
SHOWHEX ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step