Last active
May 1, 2024 00:35
-
-
Save missinglink/59d4ddb377c9f3a08365cffa6a5ec052 to your computer and use it in GitHub Desktop.
Javascript trailing zero bits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bitwise { | |
static trailingZeros8(b) { | |
let lsb = (b & -b) | |
if(lsb === 0) { return 8 } | |
return 31 - Math.clz32(lsb) | |
} | |
static trailingZeros64(a) { | |
for(let i=7; i>=0; i--) { | |
let z = Bitwise.trailingZeros8(a[i]) | |
if(z < 8) { return ((7-i) * 8) + z } | |
} | |
return 64 | |
} | |
static trailingZeros(a) { | |
let t = a.length-1 | |
for(let i=t; i>=0; i--) { | |
let z = Bitwise.trailingZeros8(a[i]) | |
if(z < 8) { return ((t-i) * 8) + z } | |
} | |
return a.length * 8 | |
} | |
} | |
Bitwise.trailingZeros64([0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment