How to check whether only 2 bits in a number at a specific position are on (edge‑case‑safe) with TypeScript

1 Answer

0 votes
/**
 * Checks if a value has exactly two bits set at pos1 and pos2, and no others.
 * * Safe against:
 * - 32-bit overflow (uses BigInt)
 * - pos1 === pos2 (logic requires two distinct bits)
 * - Out of bounds positions
 * - Extra bits set elsewhere in the number
 */
function hasExactlyTwoBits(value: bigint, pos1: number, pos2: number): boolean {
  // 1. Edge Case: Positions must be non-negative and distinct
  if (pos1 < 0 || pos2 < 0 || pos1 === pos2) {
    return false;
  }

  // 2. Create the target mask
  // We shift 1n (BigInt 1) by the required positions
  const mask = (1n << BigInt(pos1)) | (1n << BigInt(pos2));

  // 3. Comparison
  // If value matches the mask exactly, only those two bits are on.
  return value === mask;
}

// --- Examples ---
const input = 0b1000100n; // Bits at index 2 and 6 are set

console.log(hasExactlyTwoBits(input, 2, 6)); // true
console.log(hasExactlyTwoBits(input, 2, 5)); // false (pos 5 is off)
console.log(0b1010100n === (1n<<2n | 1n<<6n)); // false (extra bit at pos 4)



/*
OUTPUT:

true 
false 
false 

*/

 



answered Apr 3 by avibootz

Related questions

...