Languages
[Edit]
EN

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

12 points
Created by:
Kate_C
19790

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
    }
}

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join