2016-03-02 73 views
0

是否存在将汇编器中的值作为二进制打印的指令?到目前为止,我只找到使用ASCII字符的说明。汇编程序。打印值以二进制形式显示

我正在使用NASM。

我一直在使用。

mov ecx, var0 
mov edx, 1 
mov ebx, 1 
mov eax, 4 
int 0x80 

要打印

+1

不,没有。你将不得不写一些东西。 –

+0

有关用于打印二进制整数的算法,请参阅http://stackoverflow.com/a/4839583/224132。不管你喜欢,在汇编中实现它们。 –

回答

1

没有,没有。但是,你可以为此写一个相当简单的函数。因为我不在我的Linux机器上,所以我现在不能这样做,但这是我的方式:

首先,psuedocode。首先,让我们假设我们正在打印一个4位数字。说b1010 =(10位十进制)。我们首先要:

  1. B1010 & B1000 = B1000
  2. B1010 & b0100 = B0
  3. B1010 & B0010 = B10
  4. B1010 & B0001 = B0

所以它似乎我用4位数字,我们需要&每位与1 < <(4-我)我是指数。如果它不为零,则返回1.否则,返回0.

现在,我们只有1或0,但我们需要实际添加它以获取字符串值。最简单的方法是添加48位或0x30的ascii值“0”。在Python中,这将打印出二进制: print("\x31\x30\x31\x30")

所以,现在,我们这样做是在C:

void printBinary(uint32_t n) { 
    for (size_t i = 1; i <= 32; ++i) 
     if (n & (1 << (32 - i))) 
      printf("%c", 0x30 + 1); 
     else 
      printf("%c", 0x30 + 0); 
} 

未经测试,这是我能拿出最好的:

printBinary: 
    push ebp 
    mov ebp, esp 

    mov esi, [ebp+8] ;// __cdecl calling convention. get parameter from the stack 
    mov ecx, 1 ;// This will be used for our counter 
    .loop: 
    mov eax, 1 ;// 1 will be shifted 
    mov ebx, 32 ;// 32 is the size of the number we are printing 
    sub ebx, ecx ;// offset from the counter. 
    shl eax, ebx ;// shift left. This is the 1 << (32 - i) part in C. 
    and eax, esi ;// and it 
    test eax, eax ;// if it is zero... 
    jz .print ;// then print '0' 
    mov eax, 1 ;// otherwise, print '1' 
    .print 
    push ecx ;// save ecx counter for later 
    mov ecx, eax 
    add ecx, 0x30 
    mov eax, 4 ;// syscall for output 
    mov ebx, 1 ;// stdout 
    mov edx, 1 ;// only printing one byte 
    int 0x80 ;// call the kernel 
    pop ecx ;// replace the counter 
    inc ecx 
    cmp ecx, 32 
    jle .loop 
    mov esp, ebp 
    pop ebp 
    ret 

这是极有可能不正确在一定程度上为我还不能测试它,但希望这给你一个结构遵循。希望你可以这样称呼它:

push 10 
call printBinary 

这就是目标,无论如何。