EN
Java - how to get long max and min value with bitwise operations?
12 points
Short solution:
xxxxxxxxxx
1
long MAX_VALUE = -1L >>> 1L;
2
long MIN_VALUE = -1L << 63L;
3
4
System.out.println(MAX_VALUE); // 9223372036854775807
5
System.out.println(MIN_VALUE); // -9223372036854775808
Other short solution:
xxxxxxxxxx
1
long MAX_VALUE = ~0L >>> 1L;
2
long MIN_VALUE = ~MAX_VALUE;
3
4
System.out.println(MAX_VALUE); // 9223372036854775807
5
System.out.println(MIN_VALUE); // -9223372036854775808
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
5
long MAX_VALUE = -1L >>> 1L;
6
long MIN_VALUE = -1L << 63L;
7
8
System.out.println(MAX_VALUE); // 9223372036854775807
9
System.out.println(MIN_VALUE); // -9223372036854775808
10
11
// 0111111111111111111111111111111111111111111111111111111111111111
12
// 1000000000000000000000000000000000000000000000000000000000000000
13
System.out.println( toBinaryWithLeadingZeros(MAX_VALUE) );
14
System.out.println( toBinaryWithLeadingZeros(MIN_VALUE) );
15
}
16
17
private static String toBinaryWithLeadingZeros(long MAX_VALUE) {
18
String binaryString = Long.toBinaryString(MAX_VALUE);
19
return String.format("%64s", binaryString).replace(' ', '0');
20
}
21
}
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
5
long MAX_VALUE = ~0L >>> 1L;
6
long MIN_VALUE = ~MAX_VALUE;
7
8
System.out.println(MAX_VALUE); // 9223372036854775807
9
System.out.println(MIN_VALUE); // -9223372036854775808
10
11
// 0111111111111111111111111111111111111111111111111111111111111111
12
// 1000000000000000000000000000000000000000000000000000000000000000
13
System.out.println( toBinaryWithLeadingZeros(MAX_VALUE) );
14
System.out.println( toBinaryWithLeadingZeros(MIN_VALUE) );
15
}
16
17
private static String toBinaryWithLeadingZeros(long MAX_VALUE) {
18
String binaryString = Long.toBinaryString(MAX_VALUE);
19
return String.format("%64s", binaryString).replace(' ', '0');
20
}
21
}
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
System.out.println( Long.MAX_VALUE ); // 9223372036854775807
6
System.out.println( Long.MIN_VALUE ); // -9223372036854775808
7
}
8
}