Languages
[Edit]
EN

Java - how to get long max and min value with bitwise operations?

12 points
Created by:
Kate_C
2892

Short solution:

long MAX_VALUE = -1L >>> 1L;
long MIN_VALUE = -1L << 63L;

System.out.println(MAX_VALUE); //  9223372036854775807
System.out.println(MIN_VALUE); // -9223372036854775808

Other short solution:

long MAX_VALUE = ~0L >>> 1L;
long MIN_VALUE = ~MAX_VALUE;

System.out.println(MAX_VALUE); //  9223372036854775807
System.out.println(MIN_VALUE); // -9223372036854775808

1. Using bit shift operators

public class Example1 {

    public static void main(String[] args) {

        long MAX_VALUE = -1L >>> 1L;
        long MIN_VALUE = -1L << 63L;

        System.out.println(MAX_VALUE); //  9223372036854775807
        System.out.println(MIN_VALUE); // -9223372036854775808

        // 0111111111111111111111111111111111111111111111111111111111111111
        // 1000000000000000000000000000000000000000000000000000000000000000
        System.out.println( toBinaryWithLeadingZeros(MAX_VALUE) );
        System.out.println( toBinaryWithLeadingZeros(MIN_VALUE) );
    }

    private static String toBinaryWithLeadingZeros(long MAX_VALUE) {
        String binaryString = Long.toBinaryString(MAX_VALUE);
        return String.format("%64s", binaryString).replace(' ', '0');
    }
}

2. Using bit shift and NOT operators

public class Example2 {

    public static void main(String[] args) {

        long MAX_VALUE = ~0L >>> 1L;
        long MIN_VALUE = ~MAX_VALUE;

        System.out.println(MAX_VALUE); //  9223372036854775807
        System.out.println(MIN_VALUE); // -9223372036854775808

        // 0111111111111111111111111111111111111111111111111111111111111111
        // 1000000000000000000000000000000000000000000000000000000000000000
        System.out.println( toBinaryWithLeadingZeros(MAX_VALUE) );
        System.out.println( toBinaryWithLeadingZeros(MIN_VALUE) );
    }

    private static String toBinaryWithLeadingZeros(long MAX_VALUE) {
        String binaryString = Long.toBinaryString(MAX_VALUE);
        return String.format("%64s", binaryString).replace(' ', '0');
    }
}

3. Stanrad way of getting Long MAX and MIN value in java

public class Example3 {

    public static void main(String[] args) {

        System.out.println( Long.MAX_VALUE ); //  9223372036854775807
        System.out.println( Long.MIN_VALUE ); // -9223372036854775808
    }
}

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.