How to set specific bits in a char with Java

1 Answer

0 votes
public class BitManipulation {
    public static void main(String[] args) {
        byte ch = 0;
        ch |= (1 << 7); // Set the 7th bit
        ch |= (1 << 3); // Set the 3rd bit

        String binary = String.format("%8s", Integer.toBinaryString(ch & 0xFF))
                              .replace(' ', '0');

        System.out.println(binary);
        System.out.println("Value: " + (ch & 0xFF));
    }
}



/*
run:

10001000
Value: 13

*/

 



answered Jul 30, 2025 by avibootz
...