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

1 Answer

0 votes
public class ExactTwoBits {

    static void printBits(long value, int width) {
        String s = Long.toBinaryString(value);
        if (s.length() > width) {
            // If the number doesn't fit, truncate from the left
            s = s.substring(s.length() - width);
        }
        System.out.print(String.format("%" + width + "s", s).replace(' ', '0'));
    }

    // exactBitSet:
    // ------------
    // Returns 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).
    
    static boolean exactBitSet(int pos1, int pos2, long value) {
        if (pos1 < 0 || pos2 < 0 || pos1 >= 64 || pos2 >= 64)
            return false;

        if (pos1 == pos2)
            return false;

        long mask = (1L << pos1) | (1L << pos2);
        return value == mask;
    }

    static class Test {
        long value;
        int x, y;
        int width;

        Test(long value, int x, int y, int width) {
            this.value = value;
            this.x = x;
            this.y = y;
            this.width = width;
        }
    }

    public static void main(String[] args) {

        Test[] tests = {
            new Test(0b1000010000L, 4, 9, 10),
            new Test(0b0010000010L, 1, 7, 10),
            new Test(0b0000100100L, 2, 5, 10),
            new Test(0b1000010000L, 3, 9, 10),
            new Test(0b1001010000L, 4, 9, 10),
            new Test(0b1111111111L, 4, 9, 10),
            new Test(0b0000000000L, 4, 9, 10),
            new Test(0b1000010000L, 4, 8, 10),
            new Test(1L,            0, 0, 1),
            new Test(1L,            0, 1, 1),
            new Test(0L,            1, 1, 1)
        };

        for (Test t : tests) {
            printBits(t.value, t.width);
            System.out.print("  bits(" + t.x + ", " + t.y + ")  ->  ");
            System.out.println(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
edited Apr 3 by avibootz

Related questions

...