HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Printing integers up to 1000 and are not multiples of 5

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
areprintingmultiples1000andintegersnot

Problem

How can I shorten this?

.equ SWI_PrStr, 0x69
.equ SWI_PrInt, 0x6b
.equ StDout, 1
.equ SWI_EXIT, 0x11

.global _start
start:

MOV R5, #1
MOV R6, #1
MOV R7, #1000

LOOPHERE:

CMP R5, R7
BLE LOOPBODY
B LOOPDONE

LOOPBODY:

CMP R6, #5
BLT LOOPIF
MOV R6, #0
B LOOPNEXT

LOOPIF:

MOV R0, #StDout
MOV R1, R5
swi SWI_PrInt

ldr R1, =EOL
swi SWI_PrStr

B LOOPNEXT

LOOPNEXT:

ADD R5, R5, #1
ADD R6, R6, #1
B LOOPHERE

LOOPDONE:
swi SWI_EXIT

.data

EOL: .asciz "\n"
.end

Solution

Instead of jumping over a jump:

BLE LOOPBODY
B LOOPDONE
LOOPBODY:


you can just invert the condition and jump directly:

BGT LOOPDONE


However, as the first iteration will always happen, you can just put the check at the end of the loop instead:

LOOPHERE:

... the code in the loop

CMP R5, R7
BLE LOOPHERE


The jump to LOOPNEXT right before the label can be skipped:

B LOOPNEXT

LOOPNEXT:


So:

.equ SWI_PrStr, 0x69
.equ SWI_PrInt, 0x6b
.equ StDout, 1
.equ SWI_EXIT, 0x11

.global _start
start:

MOV R5, #1
MOV R6, #1
MOV R7, #1000

LOOPHERE:

CMP R6, #5
BLT LOOPIF
MOV R6, #0
B LOOPNEXT

LOOPIF:

MOV R0, #StDout
MOV R1, R5
swi SWI_PrInt

ldr R1, =EOL
swi SWI_PrStr

LOOPNEXT:

ADD R5, R5, #1
ADD R6, R6, #1

CMP R5, R7
BLE LOOPHERE

swi SWI_EXIT

.data

EOL: .asciz "\n"
.end

Code Snippets

BLE LOOPBODY
B LOOPDONE
LOOPBODY:
BGT LOOPDONE
LOOPHERE:

... the code in the loop

CMP R5, R7
BLE LOOPHERE
B LOOPNEXT

LOOPNEXT:
.equ SWI_PrStr, 0x69
.equ SWI_PrInt, 0x6b
.equ StDout, 1
.equ SWI_EXIT, 0x11

.global _start
start:

MOV R5, #1
MOV R6, #1
MOV R7, #1000

LOOPHERE:

CMP R6, #5
BLT LOOPIF
MOV R6, #0
B LOOPNEXT

LOOPIF:

MOV R0, #StDout
MOV R1, R5
swi SWI_PrInt

ldr R1, =EOL
swi SWI_PrStr

LOOPNEXT:

ADD R5, R5, #1
ADD R6, R6, #1

CMP R5, R7
BLE LOOPHERE

swi SWI_EXIT

.data

EOL: .asciz "\n"
.end

Context

StackExchange Code Review Q#82106, answer score: 6

Revisions (0)

No revisions yet.