-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIPRange.java
50 lines (43 loc) · 1 KB
/
IPRange.java
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
package com.linkx.tools.ip;
/**
* Created by yangxu on 6/24/14.
*/
class IPRange {
long base;
int[] offsets;
/**
* binary search
*
* @param offset
* @return
*/
public int find(int offset) {
int low = 0;
int high = offsets.length - 1; // initial partition is whole table
if (offset < offsets[low]) {
return 0;
}
if (offset > offsets[high]) { // cross two span
// not in this region
return -1;
}
boolean found = false;
int mid = 0;
while (!found && low <= high) {
mid = (low + high) >>> 1;
if (offset > offsets[mid]) {
low = mid + 1;
} else if (offset < offsets[mid]) {
high = mid - 1;
} else {
found = true;
}
}
if (found) {
return mid;
} else {
// first greater than
return low;
}
}
}