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

前端 未结 14 1827
抹茶落季
抹茶落季 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条回答
  •  被撕碎了的回忆
    2020-11-29 01:45

    My contribution - ignore previous one

    public class TestBits { 
    
        public static void main(String[] args) { 
    
            byte bit1 = 0b00000001;     
            byte bit2 = 0b00000010;
            byte bit3 = 0b00000100;
            byte bit4 = 0b00001000;
            byte bit5 = 0b00010000;
            byte bit6 = 0b00100000;
            byte bit7 = 0b01000000;
    
            byte myValue = 9;                        // any value
    
            if (((myValue >>> 3) & bit1 ) != 0) {    //  shift 3 to test bit4
                System.out.println(" ON "); 
            }
        } 
    }
    

提交回复
热议问题