是否有可能在java中有一个未签名的ByteBuffer?

use*_*111 23 java

主题说明了一切.我正在使用OpenGL和OpenCL,如果我可以使用无符号的ByteBuffer来存储数据,那么会让生活更轻松.

kan*_*arp 56

unsigned ByteBuffer示例:

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)));
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*s_D -4

这不是一个问题ByteBuffer- 即使它是未签名的- 您从中读取的每个字节都将被签名,只是因为byte已签名并且我们无法更改它。

  • 垃圾。字节就是字节。仅当符号扩展或将它们用作数值时,它们才被视为有符号。您需要做的就是将字节读入一个数字,该数字可以容纳比您想要的“无符号”字节更多的字节(“int”表示“short”,“long”表示“int”,“BigInteger”对于“长”等)。 (5认同)