-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryUtil.java
More file actions
63 lines (47 loc) · 1.54 KB
/
BinaryUtil.java
File metadata and controls
63 lines (47 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.liang.other;
/**
* 二进制处理技巧
*
* @author LiaNg
* @date 2020/6/22 16:30
*/
public class BinaryUtil {
public static void main(String[] args) {
String IP = "255.255.255.255";
long ipNum = ip2Int(IP);
System.out.println("ipNum = " + ipNum);
String realIp = int2Ip(ipNum);
System.out.println("realIp = " + realIp);
System.out.println("ipTransferToLong(IP) = " + ipTransferToLong(IP));
System.out.println("Integer.MAX_VALUE = " + Integer.MAX_VALUE);
}
public static long ip2Int(String ip) {
String[] ips = ip.split("\\.");
long res = 0;
res |= Integer.valueOf(ips[0]);
res <<= 8;
res |= Integer.valueOf(ips[1]);
res <<= 8;
res |= Integer.valueOf(ips[2]);
res <<= 8;
res |= Integer.valueOf(ips[3]);
return res;
}
public static String int2Ip(long ipNum) {
long a = ipNum & 255;
ipNum >>= 8;
long b = ipNum & 255;
ipNum >>= 8;
long c = ipNum & 255;
ipNum >>= 8;
long d = ipNum & 255;
return d + "." + c + "." + b + "." + a;
}
public static Long ipTransferToLong(String ip) {
String[] split = ip.split("\\.");
return ((Long.parseLong(split[0])<<24)+(Long.parseLong(split[1])<<16)+(Long.parseLong(split[2])<<8)+(Long.parseLong(split[3])));
}
public static String ipTransfer(Long ip) {
return ((ip >> 24) & 0xff)+"."+((ip >> 16) & 0xff)+"."+((ip >> 8) & 0xff)+"."+(ip & 0xff);
}
}