1package ds.util;
2
3import static ds.util.Boolean.toInt;
4
5
6public
7 class Integer {
8
9
10 public static int max(int i, int j) {
11 return
12 i <= j ? j : i;
13 }
14 public static int min(int i, int j) {
15 return
16 j <= i ? j : i;
17 }
18
19
20 public static int compareUnsigned(int i1, int i2) {
21 long l1 = (long)i1 & 0xFFFFFFFFl;
22 long l2 = (long)i2 & 0xFFFFFFFFl;
23
24 return
25 toInt(l1 >= l2) - toInt(l1 <= l2);
26 }
27
28
29
30
31
32
33 public static int getPrefix(int bs, int mask) {
34 return
35 bs & (~ (mask - 1) ^ mask);
36 }
37
38
39 public static int commonPrefixMask(int bs1, int bs2) {
40 return
41 zeroPrefix(bs1 ^ bs2);
42 }
43
44
45 public static boolean matchPrefix(int bs, int px, int mask) {
46 return
47 getPrefix(bs, mask) == px;
48 }
49
50
51 public static int zeroPrefix(int bs1) {
52 bs1 |= bs1 >>> 1;
53 bs1 |= bs1 >>> 2;
54 bs1 |= bs1 >>> 4;
55 bs1 |= bs1 >>> 8;
56 bs1 |= bs1 >>> 16;
57
58
59 return
60 bs1 ^ (bs1 >>> 1);
61 }
62
63 public static boolean shorterMask(int mask1, int mask2) {
64 return
65 compareUnsigned(mask1, mask2) > 0;
66 }
67
68
69
70
71
72
73 public static boolean invMask(int m) {
74 return
75 ( m != 0
76 &&
77 (m ^ (m & (~m + 1))) == 0 );
78 }
79
80
81
82
83 static final int LEN_BITSTRING = 32;
84
85 public static String toStringBS(int bs) {
86 StringBuffer res = new StringBuffer();
87 int i = LEN_BITSTRING;
88 boolean blank = false;
89
90 while ( i > 0 ) {
91 if ( blank )
92 res.append(' ');
93 --i;
94 res.append((char)(((bs >>> i) & 0x1) + (int)'0'));
95 blank = i % 8 == 0;
96 }
97 return
98 new String(res);
99 }
100
101 public static String toStringPX(int px, int mask) {
102 StringBuffer res = new StringBuffer();
103 int i = LEN_BITSTRING;
104 boolean blank = false;
105
106 while ( (((int)1 << (i - 1)) & mask) == 0 ) {
107 if ( blank )
108 res.append(' ');
109 --i;
110 res.append((char)(((px >>> i) & 0x1) + (int)'0'));
111 blank = i % 8 == 0;
112 }
113 return
114 new String(res);
115 }
116
117}