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

前端 未结 2 607
死守一世寂寞
死守一世寂寞 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.

    0 讨论(0)
  • 2021-02-04 23:35

    Write your program in C or some other language first. dont use the languages libraries, for example dont use printf("%x\n",number) to display hex, but take the number do the repeated divide by 10s as you suggest, saving them somewhere. Now remember the remainders (modulo) from dividing by ten is something between 0-9 to display this somewhere in ascii you need to add 0x30 as you mentioned. 123 becomes 12 remainder 3, then 12 becomes 1 remainder 2, and 1 becomes 0 remainder 1, 1+0x30 = 0x31 display that 2+0x30 becomes 0x32 display that, 3+0x30 becomes 0x33 display that.

    hex is no different, the base is 16 not 10. As vhallac mentions though you can mask and shift instead of using the divide operator.

    Once you have the "program" working in C or some other language, at a low level using basic operations (add, sub, divide, shift, and, or, etc) then re-write that code in assembly language.

    Eventually you may get to the point where you dont need to prove out your program in some other language and start with asm.

    0 讨论(0)
提交回复
热议问题