Java中除了char类型外,其他基本数据类型并没有提供用来处理无符号数值的API,可能有时候需要将无符号的数据转成数据流或文件,可是ByteBuffer并没有提供API来做这样的处理,我们可以自己实现使用ByteBuffer存取无符号数据。
下面是向ByteBuffer对象中存取无符号数值的工具类:
import java.nio.ByteBuffer;
public class Unsigned {
public static short getUnsignedByte(ByteBuffer buff) {
return (short) (buff.get() & 0xff);
}
public static short getUnsignedByte(ByteBuffer buff, int position) {
return (short) (buff.get(position) & (short) 0xff);
}
public static void putUnsignedByte(ByteBuffer buff, int value) {
buff.put((byte) (value & 0xff));
}
public static void putUnsignedByte(ByteBuffer buff, int position, int value) {
buff.put(position, (byte) (value & 0xff));
}
// --------------------------------------------
public static int getUnsignedShort(ByteBuffer buff) {
return buff.getShort() & 0xffff;
}
public static int getUnsignedShort(ByteBuffer buff, int position) {
return buff.getShort(position) & (short) 0xffff;
}
public static void putUnsignedShort(ByteBuffer buff, int value) {
buff.putShort((short) (value & 0xffff));
}
public static void putUnsignedShort(ByteBuffer buff, int position, int value) {
buff.putShort(position, (short) (value & 0xffff));
}
// --------------------------------------------
public static long getUnsignedInt(ByteBuffer buff) {
return buff.getInt() & 0xffffffffL;
}
public static long getUnsignedInt(ByteBuffer buff, int position) {
return buff.getInt(position) & 0xffffffffL;
}
public static void putUnsignedInt(ByteBuffer buff, int value) {
buff.putInt((int) (value & 0xffffffffL));
}
public static void putUnsignedInt(ByteBuffer buff, int position, int value) {
buff.putInt(position, (int) (value & 0xffff));
}
}
因为Java不提供无符号的byte类型,所以取出来的无符号数值要转成比它大一级的基本数据类型,getUnsignedByte()返回short类型,getUnsignedShort()返回int类型,getUnsignedInt()返回long类型。没有比long更大的基本数据类型,所以不能存取long类型的无符号数值(可以用int替代)。