# 装配中的平方根，如何移位和更改位

``````res <- 0
for i from 15 downto 0 do:
change the ith bit of result to 1
if res^2 > x then:
change the ith bit of res back to 0
return res
``````

``````sqrt:
movl \$0, %eax
movl \$15, %edx
jmp .L8
.L9

.L8
cmpq cmpq \$0, %edx
jge .L9
``````

（Intel语法，自行转换为AT＆T）

``````    mov   ebx,<number> ; *number* to find sqrt of
mov   ecx,0x8000   ; bitmask (starting with b15 bit set)
;^^^ 0x8000 = decimal 32768 = binary 1000 0000 0000 0000
xor   eax,eax      ; result <- 0
sqrt_loop:
xor   eax,ecx      ; set bit in eax
push  eax          ; store result (will be destroyed by mul)
mul   eax          ; edx:eax <- eax*eax (ignoring edx next)
cmp   eax,ebx      ; compare with *number*
pop   eax          ; restore result
jbe   keep_bit     ; res^2 <= *number* -> bit stays set
xor   eax,ecx      ; unset bit in eax
keep_bit:
shr   ecx,1        ; next bit
jnz   sqrt_loop    ; loop till all bits are tried
``````

（我没有尝试过+对其进行调试，因此可能存在一些错误。但是我认为，与您的伪算法以及通过调试重写到AT＆T一起，这应该足以使您入门。）

``````mov   ecx,15  ; i-th bit
mov   eax,1   ; set b0 (lowest bit)
shl   eax,cl  ; shift all bits (all zeroed + b0 set) cl-many times left
; eax now contains 0x8000 = b15 set, other bits zeroed
``````

0 条评论