Java: Checking if a bit is 0 or 1 in a long

前端 未结 14 1830
抹茶落季
抹茶落季 2020-11-29 01:14

What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:48

    If someone is not very comfortable with bitwise operators, then below code can be tried to programatically decide it. There are two ways.

    1) Use java language functionality to get the binary format string and then check character at specific position

    2) Keep dividing by 2 and decide the bit value at certain position.

    public static void main(String[] args) {
        Integer n =1000;
        String binaryFormat =  Integer.toString(n, 2);
        int binaryFormatLength = binaryFormat.length();
        System.out.println("binaryFormat="+binaryFormat);
        for(int i = 1;i<10;i++){
            System.out.println("isBitSet("+n+","+i+")"+isBitSet(n,i));
            System.out.println((binaryFormatLength>=i && binaryFormat.charAt(binaryFormatLength-i)=='1'));
        }
    
    }
    
    public static boolean isBitSet(int number, int position){
        int currPos =1;
        int temp = number;
        while(number!=0 && currPos<= position){
            if(temp%2 == 1 && currPos == position)
                return true;
            else{
                temp = temp/2;
                currPos ++;
            }
        }
        return false;
    }
    

    Output

    binaryFormat=1111101000
    isBitSet(1000,1)false
    false
    isBitSet(1000,2)false
    false
    isBitSet(1000,3)false
    false
    isBitSet(1000,4)true
    true
    isBitSet(1000,5)false
    false
    isBitSet(1000,6)true
    true
    isBitSet(1000,7)true
    true
    isBitSet(1000,8)true
    true
    isBitSet(1000,9)true
    true
    

提交回复
热议问题