用汇编打印十六进制数字 [英] Printing Hexadecimal Digits with Assembly
问题描述
我正在尝试学习 NASM 汇编,但似乎只是在高级语言中遇到了困难.
I'm trying to learn NASM assembly, but I seem to be struggling with what seems to simply in high level languages.
我使用的所有教科书都讨论使用字符串——事实上,这似乎是他们最喜欢的东西之一.打印hello world,大写变小写等
All of the textbooks which I am using discuss using strings -- in fact, that seems to be one of their favorite things. Printing hello world, changing from uppercase to lowercase, etc.
但是,我试图了解如何在 NASM 程序集中增加和打印十六进制数字,但不知道如何继续.例如,如果我想在十六进制中打印 #1 - n,如果不使用 C 库(我已经能够找到使用的所有引用),我该怎么做?
However, I'm trying to understand how to increment and print hexadecimal digits in NASM assembly and don't know how to proceed. For instance, if I want to print #1 - n in Hex, how would I do so without the use of C libraries (which all references I have been able to find use)?
我的主要想法是在 .data 部分有一个变量,我会继续增加它.但是如何从这个位置提取十六进制值呢?我好像需要先把它转换成字符串...?
My main idea would be to have a variable in the .data section which I would continue to increment. But how do I extract the hexadecimal value from this location? I seem to need to convert it to a string first...?
任何建议或示例代码将不胜感激.
Any advice or sample code would be appreciated.
推荐答案
首先编写一个简单的例程,它以 nybble 值 (0..15) 作为输入并输出一个十六进制字符 ('0'..'9','A'...'F').
First write a simple routine which takes a nybble value (0..15) as input and outputs a hex character ('0'..'9','A'..'F').
接下来编写一个以字节值作为输入的例程,然后调用上述例程两次以输出 2 个十六进制字符,即每个 nybble 一个.
Next write a routine which takes a byte value as input and then calls the above routine twice to output 2 hex characters, i.e. one for each nybble.
最后,对于 N 字节整数,您需要一个例程,该例程调用第二个例程 N 次,每个字节一次.
Finally, for an N byte integer you need a routine which calls this second routine N times, once for each byte.
您可能会发现先用伪代码或 HLL(如 C)表达这一点会有所帮助,然后再考虑如何将其转换为 asm,例如
You might find it helpful to express this in pseudo code or an HLL such as C first, then think about how to translate this into asm, e.g.
void print_nybble(uint8_t n)
{
if (n < 10) // handle '0' .. '9'
putchar(n + '0');
else // handle 'A'..'F'
putchar(n - 10 + 'A');
}
void print_byte(uint8_t n)
{
print_nybble(n >> 4); // print hi nybble
print_nybble(n & 15); // print lo nybble
}
print_int16(uint16_t n)
{
print_byte(n >> 8); // print hi byte
print_byte(n & 255); // print lo byte
}
这篇关于用汇编打印十六进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!