8086 Assembly (TASM): Displaying an ASCII character value as HEX

前端 未结 2 609
死守一世寂寞
死守一世寂寞 2021-02-04 23:12

** Edited for clarification and \"cleaner\" code.

I\'m trying to accept a character from the keyboard (any character) and convert it\'s ASCII value to hex, then display

2条回答
  •  野的像风
    2021-02-04 23:25

    Your logic for base 10 conversion looks good: each remainder from dividing by 10 will give you a digit, and they will be ordered from the least significant digit to the most significant one, so you need to reverse the obtained digits before printing them. Pushing them to a stack and popping them when done will do the reversing in a nice and compact way.

    For converting to hex, the operation is the same: divide by 16, get the remainder, reverse, and print. However, there are a few things to note: dividing by 16 is shifting right 4 bits. Remainder is value AND 0fH, so you don't actually need any arithmetic operations. Bit shifts and AND operation is sufficient. Moreover, you don't even need to involve the stack. You can do this from most significant nibble (four bits) to the least significant one, and print as you calculate them. The second thing that you seem to be struggling with is converting a nibble to a hex digit. Simply adding 30h is not enough. It is good enough for decimals, but for hex values, you've got the numbers 10 to 15 as well. These need to be added to 41h ('A' in ASCII) minus 10 instead. Alternatively, you can put the digits '0' to '9' and 'A' to 'F' in a table, and index them by the value of the nibble you want to print.

    You may also want to write a routine that will read a number from input. Read each digit until you read a newline, convert character to decimal value, and update an accumulator that will keep the number you've read. You will need to use this for both hex and decimal output functions.

提交回复
热议问题