如何快速将寄存器中的立即数转换为字符以存储在字符串中

How to quickly convert an immediate in a register to chars for storage in string

我的程序中有一个计数器。 我想将完成的计数器存储在一个缓冲区中,以便我可以将它发送到 mmio display.My 问题是我需要一个数字的字符表示,以便我可以将它存储在字符串缓冲区中。

为了使事情更简单,您可以先在 C 或 C++ 程序中实现您的逻辑,然后手动或借助编译器将其转换为汇编代码。

For example, translate to hex representation:

void u2hexs(unsigned n, char* buf)
{
  buf += 8;
  for (int i = 0; i < 8; i++)
  {
    unsigned digit = n & 15;
    unsigned ch = (digit < 10) ? '0' + digit : 'A' + digit - 10;
    *--buf = ch;
    n >>= 4;
  }
}

转换为:

u2hexs:
        b       $L4
        addiu   ,,8

$L8:
        addiu   ,,48
        addiu   ,,-1
        sb      ,0()
        beq     ,,$L9
        srl     ,,4

$L4:
        andi    ,,0xf
        sltu    ,,10
        bne     ,[=11=],$L8
        nop

        addiu   ,,55
        addiu   ,,-1
        sb      ,0()
        bne     ,,$L4
        srl     ,,4

$L9:
        j       
        nop

实现它的方法不止一种。您可以删除额外的分支,而是根据 sltiu 指令 returns 的值计算添加到 digit 的常量。您也许可以使用条件移动指令(movnmovz)。

您还可以定义一个包含 16 个十六进制数字(从“0”到 'F')的字符数组,并使用 digit 作为索引来提取正确的字符,从而避免所有麻烦计算加数。