Java-将值分配给固定字节数组

时间:2018-10-25 21:25:47

标签: java arrays integer byte

我正在尝试将一个整数值分配给异常的固定大小的字节数组(3)。我看到了有关ByteBuffers分配功能的信息,但是putInt尝试放入4个字节,然后由于溢出而中断了

例如:

byte[] messageLength = ByteBuffer.allocate(3).putInt(Integer.parseUnsignedInt("300")).array();

导致以下异常

Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:527)
at java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:372)

很明显,300可以容纳3个字节,因为二进制格式是0001 0010 1100。

如何将完全合法大小的整数值放入非4字节数组中?

2 个答案:

答案 0 :(得分:0)

您需要4个字节才能在字节缓冲区内分配一个Integer。 如果需要特殊的拆包规则,可以手动从字节缓冲区读取。

这是一个例子:

public static byte[] convertInts(int[] source) {
    ByteBuffer buffer = ByteBuffer.allocate(4 * source.length);
    for (int data : source) {
        buffer.putInt(data);
    }
    buffer.flip();

    byte[] destination = new byte[3 * source.length];
    for (int i = 0; i < source.length; i++) {
        buffer.get();
        destination[i * 3] = buffer.get();
        destination[i * 3 + 1] = buffer.get();
        destination[i * 3 + 2] = buffer.get();
    }

    return destination;
}

用法示例:

int[] source = {
    Integer.parseUnsignedInt("30"),
    Integer.parseUnsignedInt("300"),
    Integer.parseUnsignedInt("3000"),
    Integer.parseUnsignedInt("300000"),
};
byte[] data = convertInts(source);

答案 1 :(得分:0)

一个简单的解决方案是将Integer值转换为仅包含必要位的byte[]。以下代码适用于1、2、3和4个字节的整数:

private static byte[] compressInteger(int value) {
    if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
        return new byte[] { (byte) value };
    } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
        return new byte[] { (byte) (value >>> 8), (byte) (value) };
    } else if ((byte)(value >>> 24) == 0) {
        return new byte[] { (byte) (value >>> 16), (byte) (value >>> 8), (byte) (value) };
    } else {
        return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) (value) };
    }
}

如果要将byte[]转换回整数值,可以执行以下操作:

private static int decompressInteger(byte[] bytes) {
    int value = 0;
    for (int i = bytes.length - 1; i >= 0; i--) {
        for (int bit = 0; bit <= 7; bit++) {
            boolean isSet = ((bytes[i] >>> bit) & 1) == 1;
            if (isSet) {
                int shift = 8 * (bytes.length - 1 - i) + bit;
                int mask = 1 << shift;
                value |= mask;
            }
        }
    }
    return value;
}
相关问题