是否有可能在java中有一个未签名的ByteBuffer?
问题描述:
主题说这一切。我正在使用OpenGL和OpenCL,如果我可以只使用一个未签名的ByteBuffer来存储数据,它会使生活更轻松。是否有可能在java中有一个未签名的ByteBuffer?
答
这不是ByteBuffer
一个问题 - 即使是无符号 - 每当你从中读取字节将被签署,只是因为byte
签字,我们不能改变这种状况。
答
无符号字节缓冲区例如:
import java.nio.ByteBuffer;
public class test {
public static short getUnsignedByte(ByteBuffer bb) {
return ((short) (bb.get() & 0xff));
}
public static void putUnsignedByte(ByteBuffer bb, int value) {
bb.put((byte) (value & 0xff));
}
public static short getUnsignedByte(ByteBuffer bb, int position) {
return ((short) (bb.get(position) & (short) 0xff));
}
public static void putUnsignedByte(ByteBuffer bb, int position, int value) {
bb.put(position, (byte) (value & 0xff));
}
// ---------------------------------------------------------------
public static int getUnsignedShort(ByteBuffer bb) {
return (bb.getShort() & 0xffff);
}
public static void putUnsignedShort(ByteBuffer bb, int value) {
bb.putShort((short) (value & 0xffff));
}
public static int getUnsignedShort(ByteBuffer bb, int position) {
return (bb.getShort(position) & 0xffff);
}
public static void putUnsignedShort(ByteBuffer bb, int position, int value) {
bb.putShort(position, (short) (value & 0xffff));
}
// ---------------------------------------------------------------
public static long getUnsignedInt(ByteBuffer bb) {
return ((long) bb.getInt() & 0xffffffffL);
}
public static void putUnsignedInt(ByteBuffer bb, long value) {
bb.putInt((int) (value & 0xffffffffL));
}
public static long getUnsignedInt(ByteBuffer bb, int position) {
return ((long) bb.getInt(position) & 0xffffffffL);
}
public static void putUnsignedInt(ByteBuffer bb, int position, long value) {
bb.putInt(position, (int) (value & 0xffffffffL));
}
// ---------------------------------------------------
public static void main(String[] argv) throws Exception {
ByteBuffer buffer = ByteBuffer.allocate(20);
buffer.clear();
test.putUnsignedByte(buffer, 255);
test.putUnsignedByte(buffer, 128);
test.putUnsignedShort(buffer, 0xcafe);
test.putUnsignedInt(buffer, 0xcafebabe);
for (int i = 0; i < 8; i++) {
System.out.println("" + i + ": "
+ Integer.toHexString((int) getUnsignedByte(buffer, i)));
}
System.out.println("2: "
+ Integer.toHexString(getUnsignedShort(buffer, 2)));
System.out.println("4: " + Long.toHexString(getUnsignedInt(buffer, 4)));
}
}
答
Java不支持无符号类型。典型的解决方案是去下一个最大的类型(在你的情况下:短),只是掩盖它,所以你只使用较低的'n'(在你的情况8)位。
...但那种中断当您尝试应用到缓冲区:-(
垃圾的字节数是字节。作为签署了他们对待仅事宜时,符号扩展或使用它们作为数值。所有你需要做的就是将字节读入到一个数字中,该数字可以容纳比你想拥有“无符号”的字节更多的字节(“int”用于“short”,“long”用于“int”,“BigInteger”对于'长'等) – Thor84no 2014-02-04 18:16:00
编写一个自己的实用程序方法做&0xff是垃圾 – 2015-04-03 08:57:40
最后我发现了番石榴的好课程正在做我想要的东西http://docs.guava-libraries.googlecode.com/ git/javadoc/com/google/common/io/ByteArrayDataInput.html#readUnsignedByte%28 – 2015-04-03 09:11:06