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

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <cstdint> // uint64_t

// Returns true only if 'value' has EXACTLY TWO bits set,
// and they are *precisely* at positions pos1 and pos2 (0‑based from LSB).
bool exact_bit_set(int pos1, int pos2, std::uint64_t value) {
    // Positions must be non-negative and must refer to two distinct bit locations.
    if (pos1 < 0 || pos2 < 0 || pos1 == pos2)
        return false;

    // uint64_t has 64 bits; shifting by >= 64 is undefined.
    if (pos1 >= 64 || pos2 >= 64)
        return false;

    // Construct a mask with exactly two bits set at pos1 and pos2.
    std::uint64_t mask = (1ULL << pos1) | (1ULL << pos2);

    // The value is valid only if it matches the mask exactly:
    // no extra bits, no missing bits.
    return value == mask;
}

int main() {
    struct Test {
        std::string bits;     // human-readable binary representation
        int x, y;             // bit positions to check
        std::uint64_t value;  // numeric value to test
    };

    // A variety of test cases demonstrating correct and incorrect patterns.
    std::vector<Test> tests = {
        {"1000010000", 4, 9, 0b1000010000}, // bits at 4 and 9 set
        {"0010000010", 1, 7, 0b0010000010}, // bits at 1 and 7 set
        {"0000100100", 2, 5, 0b0000100100}, // bits at 2 and 5 set

        {"1000010000", 3, 9, 0b1000010000}, // mismatch: bit at 4, not 3
        {"1001010000", 4, 9, 0b1001010000}, // three bits set
        {"1111111111", 4, 9, 0b1111111111}, // many bits set
        {"0000000000", 4, 9, 0b0000000000}, // no bits set
        {"1000010000", 4, 8, 0b1000010000}, // wrong second position
        {"1",          0, 0, 1},            // same position twice → invalid
        {"1",          0, 1, 1},            // only bit 0 set → missing bit 1
        {"",           1, 1, 0}             // empty string, invalid positions
    };

    for (const auto& t : tests) {
        bool result = exact_bit_set(t.x, t.y, t.value);
        std::cout << (t.bits.empty() ? " " : t.bits)
                  << "  bits(" << t.x << ", " << t.y << ")  ->  "
                  << (result ? "true" : "false") << '\n';
    }
}


/*
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
   bits(1, 1)  ->  false
   
*/

 



answered Apr 3 by avibootz

Related questions

...