为什么按位与运算不适用于 Value>=8?

Why Bitwise AND operation not working for Value>=8?

此程序用于检查给定数字是否为 2 的幂。此代码在 n=7 之前正常运行,并且它为输入 n<=8 提供不相关的输出。

输入n=4; 输出:0; 预期输出:0

输入:n = 8; 输出:104; 预期输出:0

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    String s = Integer.toBinaryString(n);
    String s2 = Integer.toBinaryString(n-1);
    Integer i = Integer.parseInt(s);
    Integer j = Integer.parseInt(s2);
    System.out.println(i&j);
    input.close();
}

通过调用 toBinaryStringparseInt,您通过将数字转换为二进制来扭曲数字,然后将二进制解释为十进制。跳过这个:

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    System.out.println(n&(n-1));
    input.close();
}

不必要的从 intstring 的转换,然后是 Integer。可以直接执行bitwiseint之间的运算。看下面的代码来理解操作以及二进制转换 -

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
         System.out.print("Enter n : ");
        int n = input.nextInt();
        System.out.println("Number 1 : "+n);
        int n2= n-1;
        System.out.println("Number 2: "+n2);
        System.out.println("------Just to see the coressponding binary value-----------");
        String binaryNumber1 = Integer.toBinaryString(n);
        System.out.println("Binary Number 1 : "+binaryNumber1);
        String binaryNumber2 = Integer.toBinaryString(n2);
        System.out.println("Binary Number 1 : "+binaryNumber2);
        System.out.println("-----------------------------------------------------------");
        System.out.println("Bitwise AND operation :  "+(n & n2));   //  actual AND operation perform here
        
       
        input.close();

    }

输出

Enter n : 13
---------------------
Number 1 : 13
Number 2: 12
------Just to see the coressponding binary value-----------
Binary Number 1 : 1101
Binary Number 2 : 1100
-----------------------------------------------------------
Bitwise AND operation :  12