Search code examples
javabit-manipulationbitwise-operators

Computing maximum and minimum value of data type using bitwise operators


I'm starting to learn about the bitwise operators in Java, however, I don't quite catch the questions of computing maximum/minimum value of data types (short, byte, long , float) by using bitwise operators.

How do we start with that ? As I only found problems regarding about finding even/odd number, compute value between pairs.

Any suggestion will really help as I have spend tremendous hours just by understanding it but I haven't got anywhere so far. Not many topics about Bitwise Operators Manipulation sadly.


Solution

  • To get the largest value, fill all the bits to 1. The smallest value is the negation of the largest value.

    public class Main{
        public static void main(String[] args) {
            int value = 0;
            for(int i=0; i<31; i++) {
               value |= 1<<i;
            }
            System.out.println(value);
            System.out.println(Integer.MAX_VALUE);
            System.out.println(~value);
            System.out.println(Integer.MIN_VALUE);
        }
    }
    

    Output

    2147483647
    2147483647
    -2147483648
    -2147483648
    

    See https://www.vojtechruzicka.com/bit-manipulation-java-bitwise-bit-shift-operations/#:~:text=Java%20uses%20another%20approach%2C%20which%20is%20called%20two%27s,by%20given%20number%20of%20positions%20to%20the%20right.