Reputation: 4767
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:
...
Upvotes: 0
Views: 565
Reputation: 58750
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
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
Upvotes: 3