Java有通常的bitwise operators,所以你可以建立一个掩码和and你的数据。
编辑
也许一些示例代码会多一点有用的:
// be aware - this actually substrings a hex substring, using
// bit ops
int byteSubString(int number,
int firstPos /* 0-indexed */,
int length) {
// tricky naming as hex = 2 byte per char!
int mask = 0;
switch (length) { //lookup table/array might be best here
case 0: mask = 0; break;
case 1: mask = 0xf; break;
case 2: mask = 0xff; break;
case 3: mask = 0xfff; break;
case 4: mask = 0xffff; break;
case 5: mask = 0xfffff; break;
default: throw new IllegalArgumentException(
"Length of " + length + " not supported");
}
int tmp = (number >> (4*firstPos));
tmp = (tmp & mask);
System.out.println("Byte substring on " +
Integer.toHexString(number) +
" starting at pos " + firstPos +
" with length " + length +
" uses mask " + Integer.toHexString(mask) +
" results in " + Integer.toHexString(tmp));
return tmp;
}
当然,你也可以只呈现字符串为十六进制表示和子串。可能会更快,更易读:)