gpu.js icon indicating copy to clipboard operation
gpu.js copied to clipboard

Dirt simple implementation of clz32

Open DragonForgedTheArtist opened this issue 3 years ago • 1 comments

Not really an issue. Just thought I would help out a bit if I could. This is the same way you would implement this in hardware. You pretty much have to bit bang this to get the answer. In order to find the first zero bit of a number, you have to find the last non-zero bit and shift one.

const clz32 = gpu.createKernel(function(x) {
    let bits = 0;
    if(x === 0){
        return 32;
    }
    while(Math.pow(2,bits) <= x && bits < 32){
        bits+=1;
    }
    return 32-bits;
}).setOutput([1]);

DragonForgedTheArtist avatar Apr 05 '22 14:04 DragonForgedTheArtist

Of course once I did some experiments, looked at the source and found out that bitwise operations were supported (not documented) this might be a hair bit more optimized

const clz32 = gpu.createKernel(function(x) {
    let bits = 0;
    let curbit = 1;
    if(x === 0){
        return 32;
    }
    while(curbit <= x && bits < 32){
        curbit =curbit << 1;
        bits+=1;
    }
    return 32-bits;
}).setOutput([1]);

DragonForgedTheArtist avatar Apr 06 '22 07:04 DragonForgedTheArtist