Reputation: 9486
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());
Upvotes: 5
Views: 11854
Reputation: 5449
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;
}
Upvotes: 6
Reputation: 393781
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 int
s to negative long
s, 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
Upvotes: 4
Reputation: 265
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).
Upvotes: 3