How can I convert a long to int in Java?

后端 未结 16 2092
余生分开走
余生分开走 2020-11-29 16:49

How can I convert a long to int in Java?

相关标签:
16条回答
  • 2020-11-29 17:23

    Since Java 8 you can use: Math.toIntExact(long value)

    See JavaDoc: Math.toIntExact

    Returns the value of the long argument; throwing an exception if the value overflows an int.

    Source code of Math.toIntExact in JDK 8:

    public static int toIntExact(long value) {
        if ((int)value != value) {
            throw new ArithmeticException("integer overflow");
        }
        return (int)value;
    }
    
    0 讨论(0)
  • 2020-11-29 17:24

    Manual typecasting can be done here:

    long x1 = 1234567891;
    int y1 = (int) x1;
    System.out.println("in value is " + y1);
    
    0 讨论(0)
  • 2020-11-29 17:25

    In Java 8 I do in following way

    long l = 100L;
    int i = Math.toIntExact(l);
    

    This method throws ArithmaticException if long value exceed range of int. Thus I am safe from data loss.

    0 讨论(0)
  • 2020-11-29 17:26
    Long x = 100L;
    int y = x.intValue();
    

    0 讨论(0)
  • 2020-11-29 17:27

    Updated, in Java 8:

    Math.toIntExact(value);
    

    Original Answer:

    Simple type casting should do it:

    long l = 100000;
    int i = (int) l;
    

    Note, however, that large numbers (usually larger than 2147483647 and smaller than -2147483648) will lose some of the bits and would be represented incorrectly.

    For instance, 2147483648 would be represented as -2147483648.

    0 讨论(0)
  • 2020-11-29 17:27

    Shortest, most safe and easiest solution is:

    long myValue=...;
    int asInt = Long.valueOf(myValue).intValue();
    

    Do note, the behavior of Long.valueOf is as such:

    Using this code:

    System.out.println("Long max: " + Long.MAX_VALUE);
    System.out.println("Int max: " + Integer.MAX_VALUE);        
    long maxIntValue = Integer.MAX_VALUE;
    System.out.println("Long maxIntValue to int: " + Long.valueOf(maxIntValue).intValue());
    long maxIntValuePlusOne = Integer.MAX_VALUE + 1;
    System.out.println("Long maxIntValuePlusOne to int: " + Long.valueOf(maxIntValuePlusOne).intValue());
    System.out.println("Long max to int: " + Long.valueOf(Long.MAX_VALUE).intValue());
    

    Results into:

    Long max: 9223372036854775807
    Int max: 2147483647
    Long max to int: -1
    Long maxIntValue to int: 2147483647
    Long maxIntValuePlusOne to int: -2147483648
    
    0 讨论(0)
提交回复
热议问题