Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform int to long in Java?

Tags:

java

Many convert string ip to long java code demo like this

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

why we don't use other Java method instead method int2long? e.g.

Integer a = 0;
Long.valueof(a.toString());
like image 301
Ryanqy Avatar asked Oct 30 '17 10:10

Ryanqy


3 Answers

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

is a fancy way of writing

long val = (long) myIntValue;

Problem is that a negative int value will remain negative if you do this kind of thing, the method int2long is converting a signed int to an unsigned long which is different from that.

Personally I think it would be simpler to initially work with longs instead of working on ints, i.e. something like this:

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;
}
like image 184
Lothar Avatar answered Nov 03 '22 00:11

Lothar


str2Ip may return a negative int value. The int2long method you posted treats the input int as an unsigned int (though Java doesn't have unsigned int), and thus returns a positive long.

Converting the result of str2Ip directly to Long as you suggest (or simply casting the int to long or using Number's longValue()) will convert negative ints to negative longs, which is a different behavior.

BTW, your int2long method can be simplified to:

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

For example, the output of the following:

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

is

4278255873
-16711423
like image 44
Eran Avatar answered Nov 03 '22 01:11

Eran


You can use the longValue() method of the Number class. This means the method is available on any Number class child, including Integer. Note that this will not work with primitive types (e.g. int).

like image 36
Ivo Valchev Avatar answered Nov 03 '22 01:11

Ivo Valchev