I'm "playing" with ARM assembly on a Raspberry Pi, reading various tutorials and posts to help - no, it's not a college assignment, I'm too old for college! I'm pleased with getting the following code to take a decimal value (between 0 and 255) and output the binary string equivalent to the screen using
printf() but curious to know though whether those more experienced would consider this a "naive" solution? Are there any "gotchas"? Any better ways of tackling the problem?
I reckon there should be a better way of declaring the string to hold the output and how the string is built from the LSB (using R9)
/* dectobin2.s */ /* ------------------------------------------------------------ */ /* Converts a decimal number to binary and outputs to screen */ /* ============================================================ */ .data .balign 4 value: .word 0 binStr: .asciz "00000000" output: .asciz "%d in binary is %s\n" title: .asciz "DECIMAL TO BINARY CONVERTER\n\n" lr_temp: .word 0 lr_local: .word 0 prompt: .asciz "Enter a positive value (0-255) > " pattern: .asciz "%d" .text @ function to convert given value into a binary string decToBin: @ save the link register ldr r2, =lr_local str lr, [r2] @ set data values mov r4, r0 @ value in r4 for processing mov r9, #7 @ LSB position in output string _loop: @ repeated division by 2 2 movs r4, r4, lsr #1 @ divide by 2, set carry bcs _odd @ if carry set, remainder is 1 _even: mov r5, #0 @ remainder of 0 b _toString _odd: mov r5, #1 @ remainder of 1 _toString: add r5, #48 @ convert remainder to ASCII ldr r1, =binStr @ address of binary string strb r5, [r1, r9] @ store remainder in string at pos in r9 sub r9, r9, #1 @ move to next position in output string cmp r4, #0 @ reached zero? ble _endloop b _loop _endloop: @ restore the link register ldr lr, =lr_local ldr lr, [lr] bx lr .global main main: @ store the link register ldr r1, =lr_temp str lr, [r1] @ print a title ldr r0, =title bl printf _getValue: @ get the value to convert ldr r0, =prompt @ prep the arguments for scanf bl printf ldr r0, =pattern ldr r1, =value bl scanf @ check for valid input (0-255) ldr r0, =value ldr r0, [r0] cmp r0, #255 @ must be <= 255 bgt _getValue cmp r0, #0 @ must be >= 0 blt _getValue _isValid: @ call the function, value is in R0 bl decToBin @ display output ldr r0, =output @ get address of output string ldr r1, =value @ get the original value ldr r1, [r1] @ for first parameter ldr r2, =binStr @ get the binary string bl printf @ print the result @ restore the link register and exit ldr lr, =lr_temp ldr lr, [lr] bx lr .global printf .global scanf ```