
Software Optimization Guide for AMD64 Processors | 25112 Rev. 3.06 September 2005 |
8.5Efficient 64-Bit Integer Arithmetic in 32-Bit Mode
Optimization
The following section contains a collection of code snippets and subroutines showing the efficient implementation of
Addition, subtraction, negation, and shifting are best handled by inline code. Multiplication, division, and the computation of remainders are less common operations and are usually implemented as subroutines. If these subroutines are used often, the programmer should consider inlining them. Except for division and remainder calculations, the following code works for both signed and unsigned integers. The division and remainder code shown works for unsigned integers, but can easily be extended to handle signed integers.
64-Bit Addition
;Add ECX:EBX to EDX:EAX, and place sum in EDX:EAX. add eax, ebx
adc edx, ecx
64-Bit Subtraction
;Subtract ECX:EBX from EDX:EAX and place difference in EDX:EAX. sub eax, ebx
sbb edx, ecx
64-Bit Negation
;Negate EDX:EAX. not edx
neg eax
sbb edx,
64-Bit Left Shift
;Shift EDX:EAX left, shift count in ECX (count
;applied modulo 64).
shld | edx, eax, cl | ; First apply shift count. | |
shl | eax, cl | ; mod | 32 to EDX:EAX |
test | ecx, 32 | ; Need to shift by another 32? | |
jz | lshift_done | ; No, | done. |
mov | edx, eax | ; Left shift EDX:EAX | |
xor | eax, eax | ; by | 32 bits |
lshift_done:
170 | Integer Optimizations | Chapter 8 |