Skip to content

Instantly share code, notes, and snippets.

@missinglink
Last active May 1, 2024 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save missinglink/59d4ddb377c9f3a08365cffa6a5ec052 to your computer and use it in GitHub Desktop.
Save missinglink/59d4ddb377c9f3a08365cffa6a5ec052 to your computer and use it in GitHub Desktop.
Javascript trailing zero bits
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