简体   繁体   English

在ARM Assembly中将整数转换为十六进制字符串

[英]Converting integer to hex string in ARM Assembly

I am trying to figure out how to convert a 32 bit integer into its hex representation. 我试图弄清楚如何将32位整数转换为其十六进制表示形式。 I know that I need to separate the last 4 bits, use a switch case to find which hex character it corresponds to. 我知道我需要将最后4位分开,使用开关盒来查找它对应的十六进制字符。 And then I need to repeat this for each of the 4 bits. 然后我需要对4位中的每位重复此操作。 I am struggling to find out how to get each of the 4 bits from LSB to MSB. 我正在努力寻找如何将4位中的每一个从LSB转换为MSB。 Can anyone help? 有人可以帮忙吗? Thanks! 谢谢!

Masking and shifting, as suggested in the comments, will get you the individual nibbles (half-bytes) that make up the word. 如注释中所建议的,屏蔽和移位将使您组成单词的各个半字节(半字节)。 But to print the number using putchar or equivalent, you'll need to convert these nibbles to ASCII characters. 但是,要使用putchar或等效字符打印数字,您需要将这些半字节转换为ASCII字符。 You don't need a 'switch-case' for this (or rather its equivalent in assembly language, a 'jump table'). 为此,您不需要“开关箱”(或者相当于汇编语言的“跳转表”)。 You could use a lookup table, given that there will only be 16 entries, or you could conditionally add to the nibble to form a character. 假设只有16个条目,则可以使用查找表,也可以有条件地将其添加到半字节中以形成字符。

The ASCII digits 0-9 have character codes 48-57. ASCII数字0-9的字符代码为48-57。 The uppercase letters have character codes starting at 65 for A (the lowercase letters start from 97) and of course 0xA represents the decimal value 10. So you can turn a nibble into a hex string by adding 55 to it if its value is 10 or more, and 48 otherwise. 大写字母的字符代码从A的65开始(小写字母的数字从97开始),当然0xA代表十进制值10。因此,如果其值为10或10,则可以将半字节转换为十六进制字符串更多,否则为48。 (Equivalently, add 48 unconditionally and add a further 7 to it if the resulting value is 58 or more.) (等效地,无条件地添加48,如果结果值为58或更大,则再添加7。)

You'll want to print the hex digits out starting with the most significant digit, which is the nibble in bits 28-31 of the word. 您需要从最高有效数字开始打印十六进制数字,这是该字的第28-31位中的半字节。 If you shift the whole word left by 4 bits each time you output a character then bits 28-31 will always contain the next nibble to process. 如果每次输出一个字符时将整个单词向左移4位,则位28-31将始终包含要处理的下一个半字节。

The following is untested and written off the top of my head, so no warranty, but it might set you on the right track: 以下内容未经测试,就不在我头上了,因此不作任何保证,但这可能会使您走上正轨:

    ; Assume number to be converted is in r4.  Note r4 is clobbered

    ; Initialise loop counter
    MOV   r5, #8
.loop
    ; Take most significant nibble from r4 into r0
    MOV   r0, r4, LSR #28

    ; Shift r4 for next time
    MOV   r4, r4, LSL #4

    ; For each nibble (now in r0) convert to ASCII and print
    ADD   r0, r0, #48
    CMP   r0, #58              ; did that exceed ASCII '9'?
    ADDHS r0, r0, #7           ; add 'A' - ('0'+10) if needed
    BL    putchar

    ; Decrement loop counter, loop if not zero
    SUBS  r5, r5, #1
    BNZ   .loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM