简体   繁体   中英

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. I know that I need to separate the last 4 bits, use a switch case to find which hex character it corresponds to. And then I need to repeat this for each of the 4 bits. I am struggling to find out how to get each of the 4 bits from LSB to 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. 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.

The ASCII digits 0-9 have character codes 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. (Equivalently, add 48 unconditionally and add a further 7 to it if the resulting value is 58 or more.)

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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