Reputation: 3025
I am writing a program for one of my classes in assembly(pep8). The program is supposed to take in an integer between -32,768 and 32,767, and output its binary equivalent. The code below accomplishes the task except it prints the binary number backwards.
Is there an elegant way for me to print the binary number in the correct order (ie I DONT want to store every binary digit in a local variable and then print them in reverse order).
BR main
int: .EQUATE 0 ;local variable int
out: .EQUATE 2 ;local variable out
index: .EQUATE 4 ;local variable index
stack: .EQUATE 6 ;local variable for dynamic memory allocation
main: SUBSP stack,i ;allocate memmory
LDA 0,i
STA index,s ;initialize index
DECI int,s ;get user input and store it in num
while: LDA index,s ;while (num <= 16)
CPA 16,i ;
BRGE endWhile ;
ADDA 1,i ;index++
STA index,s ;
LDA int,s ;
ANDA 0x0001,i ;modulus 2 "%2"
STA out,s ;
DECO out,s ;output results
LDA int,s ;
ASRA ;devide num by 2
STA int,s ;
BR while ;
endWhile: ADDSP stack,i ;deallocate memmory
STOP
.END
Upvotes: 1
Views: 3404
Reputation: 726669
I am not familiar with this particular kind of assembly, but printing out a binary is relatively easy in all architectures if you shift values left, and check the carry flag C
.
When you shift a register left, its most significant bit ends up in C
. Now set another register to zero, and rotate it left immediately after shifting the source value left. The most significant bit of the original value is now in the least significant bit of the register:
Register C Value
-------- - --------
00000000 x 11001010 // Initially
00000000 1 10010100 // After left-shifting the value
00000001 0 10010100 // After left-rotating the register
Output the register, set it back to zero, and continue on. This will output the bits in the correct order.
Note that this trick is available only to assembly programmers. It is inaccessible to C/C++ programmers, because the carry flag C
is out of their reach.
Upvotes: 2