Home > Back-end >  Computing maximum and minimum value of data type using bitwise operators
Computing maximum and minimum value of data type using bitwise operators

Time:09-16

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.

CodePudding user response:

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 uses another approach, which is called two's,by given number of positions to the right.

  • Related