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

1 Answer

0 votes
function printBits(value, width = 32) {
    // Validate width
    if (width <= 0 || width > 64) {
        console.error("Error: width must be between 1 and 64.");
        return;
    }

    // Ensure value is BigInt
    const v = BigInt(value);

    // Convert to binary string with zero-padding
    const binaryStr = v.toString(2).padStart(width, "0");

    process.stdout.write(binaryStr);
}

function exactBitSet(pos1, pos2, value) {
    if (pos1 < 0 || pos2 < 0 || pos1 >= 64 || pos2 >= 64) return false;
    if (pos1 === pos2) return false;

    const mask =
        (1n << BigInt(pos1)) |
        (1n << BigInt(pos2));

    return value === mask;
}

const tests = [
    { value: 0b1000010000n, x: 4, y: 9, width: 10 },
    { value: 0b0010000010n, x: 1, y: 7, width: 10 },
    { value: 0b0000100100n, x: 2, y: 5, width: 10 },
    { value: 0b1000010000n, x: 3, y: 9, width: 10 },
    { value: 0b1001010000n, x: 4, y: 9, width: 10 },
    { value: 0b1111111111n, x: 4, y: 9, width: 10 },
    { value: 0b0000000000n, x: 4, y: 9, width: 10 },
    { value: 0b1000010000n, x: 4, y: 8, width: 10 },
    { value: 1n,            x: 0, y: 0, width: 1 },
    { value: 1n,            x: 0, y: 1, width: 1 },
    { value: 0n,            x: 1, y: 1, width: 1 }
];

for (const t of tests) {
    printBits(t.value, t.width);
    process.stdout.write(`  bits(${t.x}, ${t.y})  ->  `);
    console.log(exactBitSet(t.x, t.y, t.value) ? "true" : "false");
}



/*
OUTPUT:

1000010000  bits(4, 9)  ->  true
0010000010  bits(1, 7)  ->  true
0000100100  bits(2, 5)  ->  true
1000010000  bits(3, 9)  ->  false
1001010000  bits(4, 9)  ->  false
1111111111  bits(4, 9)  ->  false
0000000000  bits(4, 9)  ->  false
1000010000  bits(4, 8)  ->  false
1  bits(0, 0)  ->  false
1  bits(0, 1)  ->  false
0  bits(1, 1)  ->  false
   
*/

 



answered Apr 3 by avibootz

Related questions

...