{"id":10576,"library":"bit-twiddle","title":"Bit Twiddling Hacks","description":"The `bit-twiddle` package provides a highly optimized collection of fundamental bit manipulation functions, ported primarily from Stanford's extensive \"Bit Twiddling Hacks\" guide. It offers utilities for common bitwise operations such as computing the sign of an integer, absolute value, checking if a number is a power of two, logarithmic approximations (`log2`, `log10`), population count (`popCount`), and finding the next or previous power of two. Additionally, it includes specialized functions for interleaving and deinterleaving bits (`interleave2`, `interleave3`), crucial for efficient spatial indexing schemes like quadtrees and octrees (Z-order curves). The current stable version is 1.0.2, published in 2014. Due to the static nature of bitwise algorithms and the package's age, it is considered abandoned, with no active development or planned release cadence. Its primary differentiator remains its direct, performant JavaScript implementations of these classic algorithms, making it valuable for performance-critical numerical computing or graphics applications where low-level bit manipulation is essential.","status":"abandoned","version":"1.0.2","language":"javascript","source_language":"en","source_url":"git://github.com/mikolalysenko/bit-twiddle","tags":["javascript","bit","twiddle","hacks","graphics","logarithm","exponent","base 2","binary"],"install":[{"cmd":"npm install bit-twiddle","lang":"bash","label":"npm"},{"cmd":"yarn add bit-twiddle","lang":"bash","label":"yarn"},{"cmd":"pnpm add bit-twiddle","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM environments, use named imports. For CommonJS, destructure from the `require`'d object. The package itself is primarily CommonJS.","wrong":"const sign = require('bit-twiddle').sign;","symbol":"sign","correct":"import { sign } from 'bit-twiddle';"},{"note":"The entire module's exports are available as named exports in ESM, or properties on the object returned by `require()` in CommonJS.","wrong":"const bitTwiddle = require('bit-twiddle');\nconst isPow2 = bitTwiddle.isPow2;","symbol":"isPow2","correct":"import { isPow2 } from 'bit-twiddle';"},{"note":"There is no default export; all functions are named exports. Attempting a default import will result in `undefined`.","wrong":"import interleave2 from 'bit-twiddle';","symbol":"interleave2","correct":"import { interleave2, deinterleave2 } from 'bit-twiddle';"}],"quickstart":{"code":"import { sign, isPow2, nextPow2, popCount, interleave2, deinterleave2 } from 'bit-twiddle';\n\n// Basic bitwise operations\nconsole.log('Sign of -5:', sign(-5)); // Expected: -1\nconsole.log('Is 16 a power of 2?', isPow2(16)); // Expected: true\nconsole.log('Is 15 a power of 2?', isPow2(15)); // Expected: false\nconsole.log('Next power of 2 for 27:', nextPow2(27)); // Expected: 32\nconsole.log('Number of set bits in 42 (00101010b):', popCount(42)); // Expected: 3\n\n// Z-order curve (quadtree/octree) indexing\nconst x = 12;\nconst y = 25;\nconst interleaved = interleave2(x, y);\nconsole.log(`Interleaving (x=${x}, y=${y}): ${interleaved} (binary: ${interleaved.toString(2)})`);\n\nconst deinterleavedX = deinterleave2(interleaved, 0);\nconst deinterleavedY = deinterleave2(interleaved, 1);\nconsole.log(`Deinterleaving: x=${deinterleavedX}, y=${deinterleavedY}`);\n\n// Demonstrating 32-bit integer limits (JavaScript bitwise operations clamp to 32-bit)\nconst largeNum = 2 ** 31 - 1; // Max signed 32-bit int\nconsole.log(`PopCount for max signed 32-bit int (${largeNum}):`, popCount(largeNum));\n\nconst exceedingNum = 2 ** 32; // Exceeds signed 32-bit int range in bitwise ops\nconsole.log(`Is 2^32 a power of 2 (conceptually)? ${isPow2(exceedingNum)}. Actual bitwise value for isPow2 is based on 32-bit interpretation.`, isPow2(exceedingNum));","lang":"javascript","description":"Demonstrates several core bit-twiddle functions including sign, power-of-2 checks, population count, and 2D bit interleaving/deinterleaving for spatial indexing."},"warnings":[{"fix":"Be aware of JavaScript's 32-bit integer limits for bitwise operations. If working with numbers beyond this range, consider alternative libraries or custom implementations that handle larger integer types.","message":"All bitwise operations in JavaScript implicitly convert numbers to signed 32-bit integers before operating, and then convert the result back to a 64-bit floating-point number. This means values outside the range of -2,147,483,648 to 2,147,483,647 might yield unexpected results if not accounted for, particularly for functions like `isPow2` or `popCount` when applied to very large numbers.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Do not use `log2` or `log10` for precise mathematical calculations. For exact logarithms, use `Math.log2()` or `Math.log10()` (or `Math.log(v) / Math.log(base)`).","message":"The `log2(v)` and `log10(v)` functions return an 'integer approximation' of the logarithm. This is not a precise floating-point logarithm but a quick bitwise estimate, suitable for certain performance-critical algorithms where exactness is not paramount.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For new projects, consider using a more actively maintained bitwise utility library (e.g., `bitwise` or custom implementations) or carefully evaluate if the performance benefits of this specific library outweigh the risks of using unmaintained code. Always thoroughly test performance critical sections.","message":"This package has not been updated since 2014 and is considered abandoned. While bit twiddling hacks are generally stable, there are no guarantees of future maintenance, bug fixes, or performance improvements. Modern JavaScript engines might have optimized built-in operations that approach or exceed the performance of some of these hacks, or newer, maintained libraries might offer similar functionality with better support.","severity":"deprecated","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For CommonJS, use `const { sign } = require('bit-twiddle');` or `const bitTwiddle = require('bit-twiddle'); const sign = bitTwiddle.sign;`","cause":"Attempting to use named imports (e.g., `import { sign } from 'bit-twiddle';`) in a CommonJS-only environment (e.g., Node.js without a bundler or `\"type\": \"module\"` in `package.json`).","error":"TypeError: Cannot read properties of undefined (reading 'sign')"},{"fix":"Use ESM import syntax: `import { sign } from 'bit-twiddle';` Ensure your environment correctly handles ESM modules (e.g., Node.js v12+ or a bundler).","cause":"Attempting to use CommonJS `require()` syntax in an ESM module context (e.g., a `.mjs` file or a project with `\"type\": \"module\"` in `package.json`).","error":"ReferenceError: require is not defined"}],"ecosystem":"npm"}