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

1 Answer

0 votes
#include <stdio.h>
#include <stdint.h>
#include <string.h>

/*
    exact_bit_set:
    ----------------
    Returns 1 (true) only if:

      • pos1 and pos2 are valid (>= 0, < 64, and not equal)
      • value has EXACTLY those two bits set
      • all other bits are OFF

    Bit positions are ZERO‑BASED from the RIGHT (LSB = position 0).
*/
int exact_bit_set(int pos1, int pos2, uint64_t value) {
    if (pos1 < 0 || pos2 < 0 || pos1 >= 64 || pos2 >= 64)
        return 0;   // invalid positions

    if (pos1 == pos2)
        return 0;   // must be two distinct bits

    uint64_t mask = (1ULL << pos1) | (1ULL << pos2);
    
    return value == mask;
}

/* Convert a binary string (e.g., "1000010000") to uint64_t */
uint64_t bin_to_uint64(const char *s) {
    uint64_t v = 0;
    while (*s) {
        v = (v << 1) | (*s == '1' ? 1ULL : 0ULL);
        s++;
    }
    
    return v;
}

int main(void) {
    struct Test {
        const char *bits;
        int x, y;
    };

    struct Test tests[] = {
        {"1000010000", 4, 9},
        {"0010000010", 1, 7},
        {"0000100100", 2, 5},
        {"1000010000", 3, 9},
        {"1001010000", 4, 9},
        {"1111111111", 4, 9},
        {"0000000000", 4, 9},
        {"1000010000", 4, 8},
        {"1",          0, 0},
        {"1",          0, 1},
        {"",           1, 1}
    };

    int count = sizeof(tests) / sizeof(tests[0]);

    for (int i = 0; i < count; i++) {
        const char *bits = tests[i].bits;
        uint64_t value = bin_to_uint64(bits);
        int x = tests[i].x;
        int y = tests[i].y;

        int result = exact_bit_set(x, y, value);

        printf("%s  bits(%d, %d)  ->  %s\n",
               strlen(bits) ? bits : " ",
               x, y,
               result ? "true" : "false");
    }

    return 0;
}


/*
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

...