Skip to content

Instantly share code, notes, and snippets.

@ollpu
Last active June 6, 2017 21:04
Show Gist options
  • Save ollpu/b7dfb4e73edc28b41c46262be5c8df08 to your computer and use it in GitHub Desktop.
Save ollpu/b7dfb4e73edc28b41c46262be5c8df08 to your computer and use it in GitHub Desktop.
ARM assembly mathematical expression evaluator (addition, subtraction, multiplication, brackets)
.data
output_format:
.asciz "%d\n"
.balign 4
.text
parse_number:
// while numeric, mul register by 10, add number
mov r1, #0
1: // Check numeric
ldrb r2, [r0]
subs r2, #'0'
bmi 3f
cmp r2, #9
bhi 3f
2: // Is numeric
mov r3, #10
mul r1, r1, r3
add r1, r1, r2
add r0, #1
b 1b
3: // Non-numeric -> exit
bx lr
parse_expression:
push {r4, r5, r6, lr}
mov r1, #0 // r1 contains current sum
mov r2, #1 // r2 contains current product
mov r5, #1 // flag for leading unary operator
1: // Check current symbol
ldrb r4, [r0]
2: // (
cmp r4, #'('
bne 3f
// Evaluate nested expression within brackets
add r0, r0, #1
push {r1, r2}
bl parse_expression
mov r3, r1 // Move return value to r3
pop {r1, r2}
mul r2, r3, r2
mov r5, #0
b 1b
3: // )
cmp r4, #')'
bne 4f
// End bracket, expression ends
add r0, r0, #1
b 8f
4: // +
cmp r4, #'+'
bne 5f
// Add current product to the sum, clear it to 1
cmp r5, #1
addne r1, r1, r2
mov r2, #1
add r0, r0, #1
b 1b
5: // -
cmp r4, #'-'
bne 6f
// Add current product to the sum, clear it to -1
cmp r5, #1
addne r1, r1, r2
mov r2, #-1
add r0, r0, #1
b 1b
6: // *
cmp r4, #'*'
bne 7f
// Skip symbol (continue current product)
add r0, r0, #1
b 1b
7: // 0-9
cmp r4, #'0'
bmi 8f
cmp r4, #'9'
bhi 8f
// Read number, multiply it to the current product
push {r1, r2}
bl parse_number
mov r3, r1 // Move return value to r3
pop {r1, r2}
mul r2, r3, r2
mov r5, #0
b 1b
8: // Exit expression
add r1, r1, r2
pop {r4, r5, r6, pc}
.global main
main:
push {r10, lr}
ldr r0, input_ptr
bl gets
bl parse_expression
ldr r0, output_format_ptr
bl printf
pop {r10, pc}
.balign 4
input_ptr: .word input
output_format_ptr: .word output_format
.global gets
.global printf
.bss
input: .skip 256
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment