2014-04-10 5 views
-2

10 진수를 2 진수 변환기에 쓰려고하는데 일부 숫자의 경우 작동하며 다른 경우에는 그렇지 않습니다. 0 - 8 mumbers는 잘 작동하지만, 9를 입력하면 101을 표시합니다. 나는 몇 시간 동안이 코드를 고치려고 노력해 왔으며, 무엇이 잘못되었는지 알 수 없습니다.어셈블리에서 이진수로 10 진수를 변환합니다.

SYSEXIT = 1 
SYSREAD = 3 
SYSWRITE = 4 
STDOUT = 1 
STDIN = 0 

.bss         
.equ bufsize, 32    
.lcomm buf, bufsize    #buf - saved user input 

.equ buf2size, 32    
.lcomm buf2, buf2size   #binary in wrong order 

.equ buf3size, 32    
.lcomm buf3, buf2size   #binary correct order 

.data 

msg_podaj: 
.ascii "Wprowadz liczbe:\n" 
msg_dlpodaj = .- msg_podaj 

msg_test: 
.ascii "TEST\n" 
msg_dltest = .- msg_test 

.text 
.global _start 

_start: 


mov $SYSWRITE, %eax        
mov $STDOUT, %ebx 
mov $msg_podaj, %ecx 
mov $msg_dlpodaj, %edx 
int $0x80 

mov $SYSREAD, %eax        
mov $STDIN, %ebx 
mov $buf, %ecx 
mov $bufsize, %edx 
int $0x80 

xor %eax, %eax 
xor %ecx, %ecx 

mov $0, %edi        
movb buf(,%edi,), %al     
sub $48, %eax       

read: 
incl %edi            
movb buf(,%edi,), %cl     
sub $48, %ecx 


cmp $0, %cl        
jl tu         
cmp $9, %cl        
jg tu        

imul $10, %eax       
add %ecx, %eax       

jmp read 

tu: 

mov $0, %edi        
mov $0, %edx 
mov $2, %ebx 

cmp $0, %eax 
je wstaw 

movb $'1', buf3(,%edi,) 
jmp loop 

wstaw: 
movb $'0', buf3(,%edi,) 

loop: 
cmp $1, %eax 
jle changeorder 

incl %edi 
DIV %ebx 
mov %edx, buf2(,%edi,) 
add $'0', buf2(,%edi,) 

jmp loop 

changeorder: 
mov $1, %esi 

loop2: 
cmp $0, %edi 
je display 

movb buf2(,%edi,), %ah 
movb %ah, buf3(,%esi,) 
incl %esi 
decl %edi 
jmp loop2 

display: 
mov $SYSWRITE, %eax 
mov $STDOUT, %ebx 
mov $buf3, %ecx 
mov $buf3size, %edx 
int $0x80 

exit:           
mov $SYSEXIT, %eax 
int $0x80 

답변

0

코드가 간단해질 수 있습니다 (간단한 코드는 일반적으로 실수를 찾는 것이 더 간단합니다). 다음은이 일을 쉬운 방법의 개요가이다 (I은 86 어셈블리에서 그것을 구현하는 당신에게 그것을 떠날거야)

void to_bin_string(unsigned input) { 
    char output[33]; 

    // The number of binary digits needed to represent the input number, if we 
    // exclude leading zeroes. 
    unsigned digits = highest_set_bit(input) + 1; 

    // Shift the input so that the most significant set bit is in bit 31. 
    input <<= (32 - digits); 

    for (unsigned i = 0; i < digits; i++) { 
    // If the current msb is set, store a '1' in the output buffer. Otherwise 
    // store a '0'. 
    output[i] = (input & 0x80000000) ? '1' : '0'; 
    // Move the second-most significant bit into the msb position. 
    input <<= 1; 
    } 
    output[digits] = '\0'; 
} 

당신은 86 CPU에서 highest_set_bit을 계산하기 BSR 명령을 사용할 수 있습니다. & 작업은 AND 또는 TEST으로 수행 할 수 있으며 <<SHL이됩니다.

ASCII 문자열 (예 : mov %edx, buf2(,%edi,)이 아닌 경우)에 액세스 할 때는 일반적으로 바이트 연산을 사용해야합니다.

+0

asm 버전에서는 시프트가 MSB를 캐리 플래그에 쓰는 사실을 사용할 수 있습니다. – Jester

관련 문제