将 n 个最低有效位设置为 1 [英] Set n least significant bits to 1
本文介绍了将 n 个最低有效位设置为 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将寄存器的前 N 位设置为 1.例如,如果 N 是 3,那么寄存器将是:...00000111
.是否有说明或简短的方法来做到这一点?我目前的做法是:
I want to set the first N bits of a register to 1. For example, if N is 3 then the register would be: ...00000111
. Is there an instruction or short-form way to do this? The way I'm currently doing it is:
mov $0, %eax
test %esi, %esi
jz end
loop:
add $0b1, %eax
dec %esi
jz end_loop
shl %eax
jmp loop
exit:
...
推荐答案
一个有用的数学事实是,具有 N 个低位 1 位的值比 2 的幂小 1,您可以通过移位得到.所以你可以简单地将计数加载到 %cl
中并执行
A useful mathematical fact is that a value with N low-order 1 bits is 1 less than a power of two, which you can get by shifting. So you can simply load the count into %cl
and do
mov $1, %eax
shl %cl, %eax
dec %eax
当然,如果计数 N 是在汇编时已知的常数,那么让汇编器进行数学运算并加载结果:
Of course if the count N is a constant known at assembly time, then let the assembler do the math and just load the result:
mov $((1 << N) - 1), %eax
这篇关于将 n 个最低有效位设置为 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文