How to get the 4 least significant bits in a byte with Java

1 Answer

0 votes
public class Program {
    public static void main(String[] args) {
        byte value = (byte) 0b11010110;
        int lower4 = value & 0x0F;

        System.out.println("value  (dec): " + value);
        System.out.println("lower4 (dec): " + lower4);

        System.out.println("value  (bin): " + String.format("%8s",
                Integer.toBinaryString(value & 0xFF)).replace(' ', '0'));

        System.out.println("lower4 (bin): " + String.format("%4s",
                Integer.toBinaryString(lower4)).replace(' ', '0'));
    }
}



/*
run:

value  (dec): -42
lower4 (dec): 6
value  (bin): 11010110
lower4 (bin): 0110

*/

 



answered Dec 28, 2025 by avibootz
...