/**
* Copyright (c): Uwe Schmidt, FH Wedel
*
* You may study, modify and distribute this source code
* FOR NON-COMMERCIAL PURPOSES ONLY.
* This copyright message has to remain unchanged.
*
* Note that this document is provided 'as is',
* WITHOUT WARRANTY of any kind either expressed or implied.
*/
package ds.util;
import static ds.util.Boolean.toInt;
public
class Integer {
// min and max become obsolete with Java 8
public static int max(int i, int j) {
return
i <= j ? j : i;
}
public static int min(int i, int j) {
return
j <= i ? j : i;
}
// second try
public static int compareUnsigned(int i1, int i2) {
long l1 = (long)i1 & 0xFFFFFFFFl;
long l2 = (long)i2 & 0xFFFFFFFFl;
return
toInt(l1 >= l2) - toInt(l1 <= l2);
}
//----------------------------------------
// bitstring operations
// unsed in IntMap implementation
// access the leading bits of a word
public static int getPrefix(int bs, int mask) {
return
bs & (~ (mask - 1) ^ mask);
}
// compute the mask identifying the common prefix of two words
public static int commonPrefixMask(int bs1, int bs2) {
return
zeroPrefix(bs1 ^ bs2);
}
// compare the leading part of a word with a prefix
public static boolean matchPrefix(int bs, int px, int mask) {
return
getPrefix(bs, mask) == px;
}
// remove all bits set except the most significant
public static int zeroPrefix(int bs1) {
bs1 |= bs1 >>> 1;
bs1 |= bs1 >>> 2;
bs1 |= bs1 >>> 4;
bs1 |= bs1 >>> 8;
bs1 |= bs1 >>> 16;
// bs1 |= bs1 >>> 32; // needed for long
return
bs1 ^ (bs1 >>> 1);
}
public static boolean shorterMask(int mask1, int mask2) {
return
compareUnsigned(mask1, mask2) > 0;
}
//----------------------------------------
// a mask is a int which has set a single bit
// the mask is used for indexing a single bit within a word
// or to access all leading bit downto the bit index
public static boolean invMask(int m) {
return
( m != 0
&&
(m ^ (m & (~m + 1))) == 0 );
}
//----------------------------------------
// test output for bitstrings
static final int LEN_BITSTRING = 32; // int
public static String toStringBS(int bs) {
StringBuffer res = new StringBuffer();
int i = LEN_BITSTRING;
boolean blank = false;
while ( i > 0 ) {
if ( blank )
res.append(' ');
--i;
res.append((char)(((bs >>> i) & 0x1) + (int)'0'));
blank = i % 8 == 0;
}
return
new String(res);
}
public static String toStringPX(int px, int mask) {
StringBuffer res = new StringBuffer();
int i = LEN_BITSTRING;
boolean blank = false;
while ( (((int)1 << (i - 1)) & mask) == 0 ) {
if ( blank )
res.append(' ');
--i;
res.append((char)(((px >>> i) & 0x1) + (int)'0'));
blank = i % 8 == 0;
}
return
new String(res);
}
}