Bit twiddling hacks for JavaScript


This is a collection of miscellaneous bit twiddling hacks ported to JavaScript, mostly taken from here:


Via npm:

npm install bit-twiddle


Computes the sign of the integer v. Returns:

  • -1 if v < 0
  • 0 if v === 0
  • +1 if v > 0

Returns the absolute value of the integer v

Computes the minimum of integers x and y

Computes the maximum of integers x and y

Returns true if v is a power of 2, otherwise false.

Returns an integer approximation of the log-base 2 of v

Returns log base 10 of v.

Counts the number of bits set in v

Counts the number of trailing zeros.

Rounds v up to the next power of 2.

Rounds v down to the previous power of 2.

Computes the parity of the bits in v.

Reverses the bits of v.

Interleaves a pair of 16 bit integers. Useful for fast quadtree style indexing. (See wiki: )

Deinterleaves the bits of v, returns the nth part. If both x and y are 16 bit, then it is true that:

deinterleave2(interleave2(x,y), 0) === x
deinterleave2(interleave2(x,y), 1) === y

Interleaves a triple of 10 bit integers. Useful for fast octree indexing.

Same deal as deinterleave2, only for triples instead of pairs

Returns next combination ordered colexicographically.


Code is ported from Sean Eron Anderson's public domain bit twiddling hacks page. JavaScript implementation (c) 2013 Mikola Lysenko. MIT License