From: Andy 'Krazy' Glew on
On 5/25/2010 6:09 AM, Skybuck Flying wrote:

> 1. (Skybuck) Mask := not word(65535 shl BitCount); // not 1111000 =
> 0000111

Many instruction sets do not handle constants greater than some size well. Above you have a 16 bit constant.

Even though x86 handles most constants in the instruction set, larger constants cost instruction bytes.


> 2. (Michael Vinther) Mask := (1 shl BitCount)-1; // 10000-1 = 09999 = 01111
> ;) :)

This is what I would usually recommend. Although, on some machines, shifts of any form are slow.

> 3. (Skamradt) (Mask := ($FFFF shl BitCount) xor $FFFF; // 1111000 xor
> 1111111 = 0000111

Constant size.


> 4. (MitchAlsup) Mask := not word((not 0) shl BitCount); // not((not 0 =
> 1111111) shl 3 = 1111000) = 0000111

Trades off constant size for instruction count.

---

When shifts are slow, instruction sets are advised to have instructions to generate bitmasks.

dest := bitmask(frombit,tobit)

but even these have 2 6 bit constants (on a 64 bit machine).

dest := bitmask(bitpos6,len)

not much better, except for small masks.