Print ith bit of the binary number, please find the error as it is printing wrong numbers on some bits

42 Views Asked by At
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int x = 1010110;
        System.out.println("the ith bit is " + ithBit(x, n));
    }

    public static int ithBit(int x, int n) {
        int bitValue = (x & (1 << (n - 1))) != 0 ? 1 : 0;
        return bitValue;
    }

in number 1010110, its giving 4th bit=1,6th bit=1, 7th bit=0

1

There are 1 best solutions below

0
WJS On

This presumes the low order bit is the 0th bit. You don't need to use the conditional operator (?:). Just shift the result back and return the 1 or 0 directly. >>> is used to not backfill the sign bit, if detected, when shifting right. Otherwise, you would get -1 for ithBit(-1, 31);

public static int ithBit(int x, int n) {
        return  (x & (1 << n)) >>> n;
}