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

时间:2017-10-30 10:06:32

标签: java

许多人将字符串ip转换为像这样的长java代码演示

private static int str2Ip(String ip)  {
    String[] ss = ip.split("\\.");
    int a, b, c, d;
    a = Integer.parseInt(ss[0]);
    b = Integer.parseInt(ss[1]);
    c = Integer.parseInt(ss[2]);
    d = Integer.parseInt(ss[3]);
    return (a << 24) | (b << 16) | (c << 8) | d;
}

private static long ip2long(String ip)  {
    return int2long(str2Ip(ip));
}

private static long int2long(int i) {
    long l = i & 0x7fffffffL;
    if (i < 0) {
        l |= 0x080000000L;
    }
    return l;
}

为什么我们不使用其他Java方法代替方法int2long? e.g。

Integer a = 0;
Long.valueof(a.toString());

4 个答案:

答案 0 :(得分:5)

Integer a = 0;
Long.valueof(a.toString());

是一种奇特的写作方式

long val = (long) myIntValue;

问题是,如果你做这种事情,负的int值将保持为负,int2long方法是将signed int转换为unsigned long,这与此不同。

我个人认为最初使用longs而不是ints工作会更简单,例如:

private static int str2Ip(String ip)  {
    return (int) ip2long;
}

private static long ip2long(String ip)  {
    String[] ss = ip.split("\\.");
    long a, b, c, d;
    a = Long.parseLong(ss[0]);
    b = Long.parseLong(ss[1]);
    c = Long.parseLong(ss[2]);
    d = Long.parseLong(ss[3]);
    return (a << 24) | (b << 16) | (c << 8) | d;
}

答案 1 :(得分:3)

str2Ip可能会返回负值int。您发布的int2long方法将输入int视为无符号int(尽管Java没有无符号int),因此返回正{{1} }}

根据您的建议将long的结果直接转换为str2Ip(或只是将Long转换为int或使用long&#39; s Number}会将否定的longValue()转换为负int s,这是一种不同的行为。

顺便说一下,您的long方法可以简化为:

int2long

例如,输出如下:

private static long int2long(int i) {
    return i & 0xffffffffL;
}

System.out.println (ip2long("255.1.1.1"));
Integer a = str2Ip("255.1.1.1");
System.out.println (a.longValue ());

答案 2 :(得分:2)

您可以使用Number类的longValue()方法。这意味着该方法可用于任何Number类子级,包括Integer。请注意,这不适用于基本类型(例如int)。

答案 3 :(得分:1)

那怎么样?

Integer a = 10;
return 1L * a;
相关问题