Search code examples
assemblyarmtwos-complementsign-extension

Sign extend a register to 64-bit (set all bits = sign bit) in Thumb mode


I am using assembler for the ARM7TDMI (ARMv4T architecture). I'm using the Thumb mode because the ROM has a 16-bit bus (GBA). I want to sign-extend a 32-bit register to get another register with all bits set to a copy of bit 31 of the source register. The register to sign-extend is a high register, in particular R9.

I'm currently using this:

        mov     r0,r9
        mvn     r0,r0           @ sign bit needs to be inverted due to
                                @ the silly ARM carry convention
        add     r0,r0           @ copy sign bit to carry
        sbc     r0,r0           @ sign-extend R9

but that takes 4 instructions. Is there a shorter way?


Solution

  • Use an arithmetic right shift by 31 or 32 to copy the sign bit as -1 or 0 into a new register:

    mov r1, r9       @ move to a low register to be usable as an operand
    asrs r0, r1, #31 @ generate -1 or 0 in R0 depending on sign of R1