x86程序集:程序将字符作为输入返回二进制格式

时间:2015-03-23 07:15:22

标签: assembly x86

我正在执行一个C可调用程序集程序,但它没有输出正确的答案。该程序将char作为输入,然后返回该char的二进制表示。这是我的计划:

.globl _printbin
.text

_printbin:
    pushl  %ebp
    movl   %esp, %ebp
    xorl   %eax, %eax
    movl   8(%ebp), %ecx
    movl   $buffer, %edi  #move address of buffer to edi
    movl   %edi, %eax     #move edi to eax
    movl   $0x1, %ebx

loop:
    cmpb    $8, count     #compare count to 2
    je      end           #return if count == 2
    incb    count         #increment count

nibble:
    xorl %edx, %edx       #Clear out edx register
    movb %cl, %dl         
    and %bl, %dl          #And with powers of two to check for 1
    cmpb $0x0, %dl        
    jne changebit         # If dl reg is not zero change bit in buffer
    imul $0x2, %ebx
    jmp loop

changebit:
    movb $0x31, (%edi)
    incb %edi

end:
    movl   %esp, %ebp
    popl   %ebp
    ret

.data
buffer:
    .asciz "00000000"
count:
    .byte  0
.end

在C程序中这样调用:

extern char *printbin(unsigned char);

int main(char **args)
{
  unsigned int x;

  printf("number to print in binary: \n");
  x = '+';
  printf("The binary format for %x is %s\n", 
                                 x,   printbin((unsigned char)x));
  return 0;
}

但是,我得到了输出:

The binary format for 2b is 10000000

我应该获得0010 1011

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的代码存在许多问题:

  • 如果当前位为0,则不会增加edi
  • 如果当前位为1,则在存储end:后,请转到'1',而不是跳回loop:
  • 你检查位#"从右到左" (最低位优先),但将字符从左到右存储在字符串中。

工作版本可能如下所示:

_printbin:
    pushl  %ebp
    movl   %esp, %ebp
    movl   8(%ebp), %edx
    movl   $buffer, %edi  #move address of buffer to edi
    movl   %edi, %eax
    movl   $0x80, %ebx    # Mask
    movl   $8, %ecx       # Loop count

convert_byte:
    testb %bl, %dl        # Update EFLAGS based on dl AND bl
    jz no_change
    movb $'1',(%edi)
    no_change:
    inc %edi
    shrl %ebx             # ebx /= 2
    loop convert_byte     # ecx--; if ecx GOTO convert_byte

end:
    popl   %ebp
    ret