简体   繁体   English

如何在 Java 中将 long 转换为 int?

[英]How can I convert a long to int in Java?

How can I convert a long to int in Java?如何在 Java 中将 long 转换为 int?

Updated, in Java 8:在 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.但是请注意,大数字(通常大于2147483647且小于-2147483648 )将丢失一些位并且会被错误地表示。

For instance, 2147483648 would be represented as -2147483648 .例如, 2147483648将表示为-2147483648

Long x = 100L;
int y = x.intValue();

For small values, casting is enough:对于小值,强制转换就足够了:

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

However, a long can hold more information than an int , so it's not possible to perfectly convert from long to int , in the general case.但是, long可以比int更多信息,因此在一般情况下不可能完美地从long转换为int If the long holds a number less than or equal to Integer.MAX_VALUE you can convert it by casting without losing any information.如果long持有一个小于或等于Integer.MAX_VALUE您可以通过强制转换来转换它而不会丢失任何信息。

For example, the following sample code:例如,以下示例代码:

System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );

long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);

int y = (int) x;
System.out.println("int y=" + y);

produces the following output on my machine:在我的机器上产生以下输出:

largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648

Notice the negative sign on y .注意y上的负号。 Because x held a value one larger than Integer.MAX_VALUE , int y was unable to hold it.因为x持有一个比Integer.MAX_VALUE大 1 的值,所以int y无法持有它。 In this case, it wrapped around to the negative numbers.在这种情况下,它环绕到负数。

If you wanted to handle this case yourself, you might do something like:如果您想自己处理这种情况,您可以执行以下操作:

if ( x > (long)Integer.MAX_VALUE ) {
    // x is too big to convert, throw an exception or something useful
}
else {
    y = (int)x;
}

All of this assumes positive numbers.所有这些都假设为正数。 For negative numbers, use MIN_VALUE instead of MAX_VALUE .对于负数,使用MIN_VALUE而不是MAX_VALUE

Since Java 8 you can use: Math.toIntExact(long value)从 Java 8 开始,您可以使用: Math.toIntExact(long value)

See JavaDoc: Math.toIntExact 请参阅 JavaDoc:Math.toIntExact

Returns the value of the long argument;返回长参数的值; throwing an exception if the value overflows an int.如果值溢出 int 则抛出异常。

Source code of Math.toIntExact in JDK 8: JDK 8 中Math.toIntExact源代码:

public static int toIntExact(long value) {
    if ((int)value != value) {
        throw new ArithmeticException("integer overflow");
    }
    return (int)value;
}

如果使用Guava 库,有方法Ints.checkedCast(long)Ints.saturatedCast(long)用于将long转换为int

long x = 3;
int y = (int) x;

but that assumes that the long can be represented as an int , you do know the difference between the two?但是假设long可以表示为int ,您知道两者之间的区别吗?

You can use the Long wrapper instead of long primitive and call您可以使用Long包装器代替long原语并调用

Long.intValue()

Java7 intValue() docs Java7 intValue() 文档

It rounds/truncate the long value accordingly to fit in an int .它相应地舍入/截断long值以适应int

If direct casting shows error you can do it like this:如果直接投射显示错误,您可以这样做:

Long id = 100;
int int_id = (int) (id % 100000);

In Java, a long is a signed 64 bits number, which means you can store numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 (inclusive).在 Java 中,long 是一个有符号的 64 位数字,这意味着您可以存储 -9,223,372,036,854,775,808 和 9,223,372,036,854,775,807(含)之间的数字。

A int, on the other hand, is signed 32 bits number, which means you can store number between -2,147,483,648 and 2,147,483,647 (inclusive).另一方面,int 是有符号的 32 位数字,这意味着您可以在 -2,147,483,648 和 2,147,483,647(含)之间存储数字。

So if your long is outside of the values permitted for an int, you will not get a valuable conversion.因此,如果您的 long 超出了 int 允许的值,您将无法获得有价值的转换。

Details about sizes of primitive Java types here:有关原始 Java 类型大小的详细信息,请访问:

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

In Java 8 I do in following wayJava 8 中,我按照以下方式进行

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

This method throws ArithmaticException if long value exceed range of int .如果long值超出int范围,则此方法将引发ArithmaticException Thus I am safe from data loss.因此,我可以避免数据丢失。

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:请注意, Long.valueOf的行为是这样的:

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

Manual typecasting can be done here:手动类型转换可以在这里完成:

long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);

如果您想进行安全转换并享受 Java8 和 Lambda 表达式的使用,您可以像这样使用它:

val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
long x;
int y;
y = (int) x

You can cast a long to int so long as the number is less than 2147483647 without an error.只要数字小于 2147483647 且没有错误,您就可以将 long 转换为 int。

I'm adding few key details.我正在添加一些关键细节。

Basically what Java does is truncate long after 32 bits, so simple typecasting will do the trick:基本上 Java 所做的是在 32 位之后截断long ,因此简单的类型转换就可以解决问题:

    long l=100000000000000000l;
    System.out.println(Long.toString(l,2));
    int t=(int)l;
    System.out.println(Integer.toString(t,2));

Which outputs:哪些输出:

101100011010001010111100001011101100010100000000000000000
                          1011101100010100000000000000000

for l=1000000043634760000l it outputs:对于l=1000000043634760000l它输出:

110111100000101101101011110111010000001110011001100101000000
                             -101111110001100110011011000000

If we convert this -101111110001100110011011000000 in proper two's compliment we will get the exact 32-bit signed truncated from the long .如果我们将此-101111110001100110011011000000转换为适当的二进制补码,我们将得到从long中截断的精确 32 位带符号。

// Java Program to convert long to int
  
class Main {
  public static void main(String[] args) {
  
    // create long variable
    long value1 = 523386L;
    long value2 = -4456368L;
  
    // change long to int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);
      
    // print the type
    System.out.println("Converted type: "+ ((Object)num1).getClass().getName());
    System.out.println("Converted type: "+ ((Object)num2).getClass().getName());
  
    // print the int value
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}

I Also Faced This Problem.我也遇到了这个问题。 To Solve This I have first converted my long to String then to int.为了解决这个问题,我首先将 long 转换为 String,然后转换为 int。

int i = Integer.parseInt(String.valueOf(long));

long x = 3120L;长 x = 3120L; //take any long value int z = x.intValue(); //取任意长值 int z = x.intValue(); //you can convert double to int also in the same way //你也可以用同样的方式将double转换为int

if you needto covert directly then如果你需要直接转换然后

longvalue.intvalue(); longvalue.intvalue();

Long l = 100;
int i = Math.round(l);

In Spring, there is a rigorous way to convert a long to int在 Spring 中,有一种严格的方式将 long 转换为 int

not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.不仅 lnog 可以转换为 int,任何类型的类 extends Number 都可以转换为其他 Number 类型,这里我将向您展示如何将 long 转换为 int,其他类型反之亦然。

Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);

将 long 转换为 int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM