我不会在这里追求任何奇特的东西,因为这似乎是一项家庭作业(今天有两个人问了同样的问题)。这段代码应该做成一个函数,这样可以增强它的性能。由于我没有获得荣誉学位或班级 A,因此提供最佳解决方案对我来说没有意义,但您可以使用以下解决方案:
BITS_TO_DISPLAY equ 32 ; Number of least significant bits to display (1-32)
section .text
global _start ; must be declared for using gcc
_start : ; tell linker entry point
mov edx, msg_len ; message length
mov ecx, msg ; message to write
mov ebx, 1 ; file descriptor (stdout)
mov eax, 4 ; system call number (sys_write)
int 0x80 ; call kernel
mov eax, 100
mov ebx, 100
cmp ebx,eax
pushf
pop dword eax
; Convert binary to string by shifting the right most bit off EAX into
; the carry flag (CF) and convert the bit into a '0' or '1' and place
; in the save_flags buffer in reverse order. Nul terminate the string
; in the event you ever wish to use printf to print it
mov ecx, BITS_TO_DISPLAY ; Number of bits of EAX register to display
mov byte [save_flags+ecx], 0 ; Nul terminate binary string in case we use printf
bin2ascii:
xor bl, bl ; BL = 0
shr eax, 1 ; Shift right most bit into carry flag
adc bl, '0' ; bl = bl + '0' + Carry Flag
mov [save_flags-1+ecx], bl ; Place '0'/'1' into string buffer in reverse order
dec ecx
jnz bin2ascii ; Loop until all bits processed
mov edx, BITS_TO_DISPLAY ; message length
mov ecx, save_flags ; address of binary string to write
mov ebx, 1 ; file descriptor (stdout)
mov eax, 4 ; system call number (sys_write)
int 0x80
mov eax, 1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db "rubi",10
msg_len equ $ - msg
section .bss
save_flags resb BITS_TO_DISPLAY+1 ; Add one byte for nul terminator in case we use printf
这段代码背后的想法是我们不断地移动位(使用SHR指令 http://x86.renejeschke.de/html/file_module_x86_id_285.html) 在里面EAX每次向右注册一位。从寄存器移出的位被放置在进位标志 (CF) 中。我们可以用ADC http://x86.renejeschke.de/html/file_module_x86_id_4.html将进位标志 (0/1) 的值添加到 ASCII '0' 以获得 ASCII 值 '0` 和 '1'。我们以相反的顺序将这些字节放入目标缓冲区,因为我们是从右向左移动这些位。
BITS_TO_DISPLAY
可以设置在 1 到 32 之间(因为这是 32 位代码)。如果您对寄存器的底部 8 位感兴趣,请将其设置为 8。如果要显示 32 位寄存器的所有位,请指定 32。