问题
i wanted to convert a binary number to a decimal in assembly but i keep on getting zero
this is the number
aLength db "00000000000000000000000000010101", NULL
and i tried using this code to get each character and subbing by '0' multiplying by 2 and adding but it keeps saying that the answer is 0
mov rbx,aLength
mov dword[rsum],0
mov ecx,0
mov r10,32
lp:
mov cl,byte[rbx]
sub cl,'0'
mov eax,dword[rsum]
mul dword[two]
add eax,ecx
mov dword[rsum],eax
add rbx,1
dec r10
cmp r10,0
jbe lp
mov r8d,dword[rsum]
mov byte[aLength],r8b
回答1:
Your code loops only once, this is because you inverted the looping condition
cmp r10, 0
jbe lp
Should be
cmp r10, 0
ja lp
Since r10 hold the remaining number of bits to convert.
Once you change that line your code works.
That said, it can be simplified and made more readable.
One nice trick to use when converting from binary to decimal is the use of the carry flag.
Shifting instruction put the output bit (the lsb for a left shift, the msb for a right shift) into the carry flag.
Using the rcl/rcr instruction we can grab that bit and shift it back into another register.
Since the ASCII value for '1' is 31h, which is odd, hence have bit 0 set, and the ASCII value for '0' is 30h, which is even, hence have bit 0 clear; by shifting the digit ASCII value right by 1 we set the carry flag according do the intended digit value: 0 for '0' and 1 for '1'.
Now we can use rcl to shift that bit into eax.
I also prefer using whole register when possible, and put white lines between functional separated pieces of code.
Finally I capitalize memory size specifiers like WORD, DWORD, BYTE (PTR where applicable) just to easily spot memory operations.
One more: I removed all the intermediary memory access.
xor eax, eax ;Converted value (so far)
mov rbx, aLength ;Pointer to ASCII digits
mov r10, 32 ;Bits left to convert
_convert:
movzx ecx, BYTE [rbx] ;Grab a digit
add rbx, 1 ;And increment the pointer
shr ecx, 1 ;Set CF according to the digit value
rcl eax, 1 ;Shift CF into EAX from right (Rotate left)
sub r10, 1 ;Decrement count
ja _convert
;Store results
mov DWORD [rSum], eax
mov BYTE [aLength], al
来源:https://stackoverflow.com/questions/37827898/convert-ascii-binary-to-decimal-in-assembly-language