我得到了一些代码,我理解其中的大部分内容,并且知道会发生什么。我在理解这段代码时遇到问题:
div bl
and ax, 1111111100000000b
我觉得第一行只是一个简单的除法,但是和ax, 1111111100000000b
是干什么的呢?
完整代码为:
section .data
number db 5
answer db 1
section .bss
section .text
global _start
_start:
mov esi, number
keith: mov eax, 0
mov al, [esi]
mov dl, al
mov bl, 2
loopy: div bl ; ax / bl with quotient in al and remainder in ah
and ax, 1111111100000000b
cmp ax, 0
je there
inc bl
cmp bl, dl
je done
mov eax, 0
mov al, [esi]
jmp loopy
; restore the number back into
; ax
there: mov byte[answer], 0
done:
mov eax,1 ; The system call for exit (sys_exit)
mov ebx,0 ; Exit with return code of 0 (no error)
int 80h
最佳答案
我认为将它写成and ax, 0xFF00
会更清楚,因为计算八个 1 和八个 0 对人类读者来说更难。
更好的方法是 xor al,al
将低字节归零(但在写入 al< 后读取完整的
)。ax
时会产生部分寄存器减速
实际上,代码只是一种非常愚蠢的检查余数是否为零的方法。整个代码相当脑残。使用 movzx
加载高位字节清零的字节,而不是 mov eax,0
/mov al, [mem]
。
对于测试,只需test ah,ah
/je there
直接测试余数。 and ax
也设置 ZF 当且仅当余数为零,所以 and ax, 0xFF00/jz there
也是等价的。这只是糟糕的代码。
这里是一个重写:
section .data
number db 5
is_prime db 1 ; we store a zero if it's not prime
section .text
global _start
_start:
movzx edx, byte [number] ; there was no need to put the pointer in a register
mov ecx, 2
;; This whole algorithm is very naive. Slightly better: check for even (low bit), then only check odd divisors. Google for stuff that's better than trial division.
.trial_division:
mov eax, edx ; fresh copy of number. cheaper than re-loading from cache
div bl ; ax / bl. quotient in al. remainder in ah
test ah,ah ; set flags based on remainder
jz .found_divisor
inc ecx
cmp ecx, edx ; upper bound only needs to be sqrt(number), but we're aiming for small / simple code, not efficiency apparently
jl .trial_division ; the final conditional branch goes at the end of the loop
jmp done
.found_divisor:
mov byte[is_prime], 0
done:
mov eax,1 ; The system call for exit (sys_exit)
xor ebx,ebx ; Exit with return code of 0 (no error)
int 80h
所以在循环中只有一个未采取的分支,然后循环一个采取的条件分支。这无关紧要,因为 div
吞吐量是唯一的瓶颈,但通常尽可能将 insn 排除在循环之外。
关于linux - 我不明白 "and ax, 1111111100000000b"指令在做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666817/