Loading 32 bit values to a register in arm assembly

wageesha picture wageesha · Aug 1, 2016 · Viewed 17.3k times · Source

I want to load 1 32 bit hexadecimal directly into a register using arm assembly.

mov r1,#0x6c617669

This cannot be used because from this instruction we can only load 8 bit values. So I have load the 32 bit value directly from the memory. So how can I store the 32 bit value in memory and load it directly to a register using arm assembly?

I tried this code.

    .global main
main:
    sub sp,sp,#4
    str lr,[sp,#0]

    sub sp,sp,#4
    str r0,x
    add sp,sp,#4

    ldr lr,[sp,#0]
    add sp,sp,#4
    mov pc,lr

    .data
x: .word 0x6c617669

But gives the following error.

test1.s: Assembler messages: 
test1.s:45: Error: internal_relocation (type: OFFSET_IMM) not fixed up

Answer

old_timer picture old_timer · Aug 1, 2016

You have two basic choices. You can load it or build up the register 8 non-zero bits at a time

mov r0,#0x12000000             @ construct from 8-bit rotated immediates
orr r0,r0,#0x00340000
orr r0,r0,#0x00005600
orr r0,r0,#0x00000078
...

ldr r1,=0x12345678             @ let the assembler figure out how
...

ldr r3,myconst                 @ explicitly load from a nearby constant
...
myconst: .word 0x12345678

The latter two are the same, the equals trick simply asks the assembler to place the value within reach and do a pc relative load.