Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replicate PEXT (parallel bit extract) with basic bitwise ops?

I'm porting some code from Rust to Swift and I noticed they use pext method to do some bit manipulation. Since it's an Intel instruction I can't get that into my Swift code so I was wondering what set of bitwise instructions (that I can use in Swift) would be able to get the same result as a PEXT operation.

For more context, here is a description of PEXT

Basically it uses a mask that maps high order bits to contiguous lower order bits and clears the higher order bits in the final output. Example:

source = 1011 1110 1001 0011
mask =   0110 0011 1000 0101 

s = pext(source, mask)

s -> 0000 0000 0011 0101 

I know replicating an advanced instruction is a performance hit but I'm really just trying to get the code to work.

like image 435
swigganicks Avatar asked Sep 16 '26 23:09

swigganicks


1 Answers

@LưuVĩnhPhúc answer was correct. It's wildly inefficient on non-Intel architecture though so I would advise others looking to incorporate BMI2 instructions into Swift code to only do so when targeting macOS

like image 146
swigganicks Avatar answered Sep 18 '26 18:09

swigganicks