比较数字的第三位

Comparing the third bit of a number

下面的程序检查数字的第三位是否为 1。我只在第三位 (4) 取了 1 的数字,并将其与用户输入的数字进行比较。

到目前为止该程序有效,但我正在寻找不同的方法。我想知道是否有另一种方法可以得到相同的结果。

Scanner sc = new Scanner(System.in);
System.out.println("Eneter number: ");
int number = sc.nextInt();
int snum = 4;
int check = number & snum;
if (check == snum)
{
    System.out.println("The third bit 1.");
}
else
{
    System.out.println("The third bit is not 1.");
}
sc.close();

您可以将数字向右移动两位,方法是将其除以 4,然后测试最后一位(移动前的第 3 位)- 如果数字为奇数,则为 1 , 否则 - 它是 0:

num = num / 4;
if (num % 2 == 1) //it was 1
else //it was 0

不过你的方法也不错

  if((number >> 2) & 1)==1) {
       // same code as before.
   }

发生的情况是你的数字向左移动了两次所以假设你的数字是 12 --> 1100。所以在移动之后它变成 0011。现在你可以将最后一位与 1 进行比较。

有无数种方法,因为您可以插入许多冗余操作。但是如果限定为一次算术/逻辑运算加上一次相等测试/比较,有以下几种可能(test true for third bit == 1, false for third bit == 0)-

(number & 4) != 0  
(number | 4) == number  
(number % 8) >= 4