You are on page 1of 9

ASSEMBLY EXAMPLES

C code converted to assembly


Outline

• C to assembly code examples


– Sum of a sequence
– Sum of two arrays
– String copy
Example1: Sum of Sequence

{
int i, sum; MOVS r1,#0x00
sum = 0; MOVS r0,#0x01
for (i=1; i<=5; i++) { B CHK
sum = sum + i; loop ADD r1,r1,r0
} ADDS r0,r0,#1
} CHK CMP r0,#0x05
BLE loop
Example1: Sum of Sequence

{
int i, sum; MOVS r1,#0x00
sum = 0; MOVS r0,#0x01
for (i=1; i<=5; i++) { B CHK
sum = sum + i; loop ADD r1,r1,r0
} ADDS r0,r0,#1
} CHK CMP r0,#0x05
BLE loop
Example2: Sum of 2 Arrays

{
int A[10] = {9,8,7,6,5,4,3,2,1,0};
int B[10] = {1,2,3,4,5,6,7,8,9,10};
int s = 0;
int i = 0;
for (i=0; i<10; i++) {
s += A[i] * B[i];
}
}
MOVS r2,#40 ; 40 bytes size of A
LDR r1,[pc,#140] ; literal value {9,8,..} storage location
ADD r0,sp,#0x2C ; store A in the stack
BL.W memcpy ; call memcopy (dst, src, size=40B)
MOVS r2,#40 ; 40 bytes size of B
LDR r1,[pc,#128] ; literal value {9,8,..} storage location
ADDS r1,r1,#0x28 ; literal value {1,2,..} storage location
ADD r0,sp,#0x04 ; store B in the stack
BL.W memcpy ; call memcopy (dst, src, size=40B)
MOVS r5,#0x00 ; int s = 0;
MOVS r4,#0x00 ; int i = 0;
NOP
B CHK
LOOP ADD r0,sp,#0x2C ; R0 pointer to A
LDR r0,[r0,r4,LSL #2] ; R0 = A[i]
ADD r1,sp,#0x04 ; R1 pointer to B
LDR r1,[r1,r4,LSL #2] ; R1 = B[i]
MLA r5,r0,r1,r5 ; Multiply Accumulate R5 = R5 + A[i]*B[i]
ADDS r4,r4,#1 ; i++
CHK CMP r4,#0x0A ; compare i, 10
BLT LOOP ; branch less than
Example3: copy string

void copy_tring (char * src, char* dst) {


while (*src != '\n') {
*dst++ = *src++;
Local function
}
*dst = '\n';
}
char textbuffer[40] = ""; // Text buffer
int main(void) Global variable – referenced using PC
{
{
char buffer[40]; Local variable – referenced using SP
copy_tring (textbuffer, buffer);
}
}
Example3: copy string

{ Local variable – referenced using SP


char buffer[40];
copy_tring (textbuffer, buffer);
}

Global variable – referenced using PC


ADD r1,sp,#0x2C
LDR r0,[pc,#28] ; @0x08000764
BL.W copy_tring

Function call
Example3: copy string
void copy_tring (char * src, char* dst) {
while (*src != '\n') {
*dst++ = *src++;
}
*dst = '\n';
}
B CHK
LOOP LDRB r2,[r0],#0x01
STRB r2,[r1],#0x01
*dst++ = *src++;
CHK LDRB r2,[r0,#0x00]
CMP r2,#0x0A
while (*src != '\n')
BNE LOOP
STRB r2,[r1,#0x00] *dst = '\n';
BX lr return

You might also like