使用Shift-Left(shl)得到2^N,给定N?
尝试使用 Shift-Left 指令进行乘法运算。
的SHL (移位左)指令对所述目的地操作数的逻辑左移,填充的最低位为0。
我不明白如何为 N 使用寄存器或内存,因为当我尝试这样做时,我被告知“指令操作数无效”
- 用户在 RequestNumber 过程中输入一个数字 N(返回
EAX)。 - 我正在尝试的计算是:结果 = 1 * 2^N
我的代码:
mov ebx, 1
call RequestNumber ; returns eax
shl ebx, eax
mov result, ebx
我正在处理的任务要求使用 Shift 来获得结果 = 2^N 据我所知,您只能在此寄存器中使用 imm8 数字CL(尝试使用ECX具有相同结果的较低数字)。
问题:如果必须从用户那里获取N,如何正确使用Shift指令?
回答
移位量必须在cl. 因此,要从用户那里获得移位输入,请将其放在cl. 回想一下,这cl是 的低 8 位ecx,因此如果您将移位量放入ecx然后移位cl,它会按预期工作:
mov ebx, 1
call RequestNumber ; returns eax
mov ecx, eax
shl ebx, cl
mov result, ebx
-
Note that there's another way to implement `1<<n` which is slightly more efficient on Intel CPUs: `xor edx, edx` / `bts edx, eax` (EDX |= 1<<EAX). It doesn't need the count in CL specifically, and xor-zeroing is at least as cheap as `mov reg, 1`. BTS on AMD CPUs is 2 uops, so it's about break even by saving the `mov ecx,eax`.
(You don't want memory-destination BTS with a register bit-index, it's much slower. https://agner.org/optimize/)