如何检查给定位中的单个位是1还是0?

问题描述 投票:0回答:2

如何检查位数中的数字是1还是0? 例如: 给出的数字:0b00001101 位索引 0 的位置 = true 位索引 1 的位置 = false

我一直在确定钻头的位置。

java bit-manipulation bit
2个回答
0
投票

检查数字的二进制表示形式的给定位置(例如

n
)是否为 0 的一种方法是将数字移位
n
次并检查移动的最后一位数字。在例子中

public class Main {
    public static void main(String[] args) {
        System.out.println(checkPosition(Byte.parseByte(String.valueOf(3)),1));
    }
    // Return true if the given position is 0, false otherwise
    public static boolean checkPosition(Byte b, int position)    {
        return (b.byteValue() >> position) % 2 == 0;
    }
}
// Output: false

0
投票

如果您了解数字如何用二进制表示,最简单的方法是对位表示的数字使用按位 and 运算符,并将结果与数字进行比较。对于任何数字,从右侧开始,各个位代表数字 1、2、4、8、16 等,对于位 1、2、3、4、5。

int number = 9;

boolean isBitOneOn = (number & 1) == 1;
boolean isBitTwoOn = (number & 2) == 2;
boolean isBitThreeOn = (number & 4) == 4;
boolean isBitFourOn = (number & 8) == 8;
boolean isBitFiveOn = (number & 16) == 16;

在此示例中,数字 9 用二进制表示为 00001001;代表 8 和 1 的位打开。

© www.soinside.com 2019 - 2024. All rights reserved.