5

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());
Ryanqy
  • 8,476
  • 4
  • 17
  • 27
  • 1
    *"why we don't use other Java method instend method int2long?"* Because that's really inefficient, creating a string to consume it as a number? – T.J. Crowder Oct 30 '17 at 10:10
  • Possible duplicate of [How do I convert from int to Long in Java?](https://stackoverflow.com/questions/1302605/how-do-i-convert-from-int-to-long-in-java) – Ivan Aracki Oct 30 '17 at 10:16

4 Answers4

6
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;
}
Lothar
  • 5,323
  • 1
  • 11
  • 27
4

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
Eran
  • 387,369
  • 54
  • 702
  • 768
3

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).

Ivo Valchev
  • 215
  • 3
  • 11
2

and what about?

Integer a = 10;
return 1L * a;
Vadim
  • 4,027
  • 2
  • 10
  • 26