## [Math] Boolean algebra for noobs: easy exercise

New x86 instruction appeared within BMI2 set, BZHI.

Another description:

BZHI copies the bits of the first source operand (the second operand) into the destination operand (the first operand) and clears the higher bits in the destination according to the INDEX value specified by the second source operand (the third operand). The INDEX is specified by bits 7:0 of the second source operand. The INDEX value is saturated at the value of OperandSize -1.

...

N := SRC2[7:0]
DEST := SRC1
IF (N < OperandSize)
DEST[OperandSize-1:N] := 0
FI
...


( src )

It's interesting to see, how this instruction can be implemented in pure C:

uint64_t bzhi(uint64_t dest, uint64_t index)
{
return dest & ((1 << index) - 1);
};


As an exercise, find out, why this works.

###### (the post first published at 20221109.)

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.