Finding the nth LSB

Is there some secret dark instruction to find the nth LSB without looping?
We call the secret instruction get() here.

For example for this 15 bit number:

const mask: u15 = 0b0101011110010001;

const a: u4 = get(mask, 0); // returns 0
const b: u4 = get(mask, 1); // returns 4
const c: u4 = get(mask, 2); // returns 7
const d: u4 = get(mask, 3); // returns 8
// etc.

These things can be done efficiently with the upcoming pext/pdep builtins, in your case @ctz(@depositBits(1 << pos, mynum)), where @ctz already exists in Zig and counts trailing zero (pdep alone would just leave the n’th bit set, with all other bits zeroed)

The PR is actively developed: Implement @depositBits and @extractBits by bnuuydev · Pull Request #23474 · ziglang/zig · GitHub

I believe for now you’ll have to write the lookup yourself

1 Like

I was already looking at pext stuff (which could be of use in other area’s of my program as well).
Thanks!! I’ll be back here tonight I think.

1 Like