繁体   English   中英

将int转换为字节数组BufferOverflowException

[英]Convert int to byte array BufferOverflowException

我需要将我的Integer值转换为字节数组。 为了避免在每次调用intToBytes方法时一次又一次地创建ByteBuffer,我定义了一个静态ByteBuffer。

private static ByteBuffer intBuffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);

public static byte[] intToBytes(int Value)
{
    intBuffer.order(ByteOrder.LITTLE_ENDIAN);
    intBuffer.putInt(Value);
    return intBuffer.array();
}

当我运行intToBytes方法时,我得到BufferOverflowException。

W / System.err:java.nio.BufferOverflowException W / System.err:在java.nio.ByteArrayBuffer.putInt(ByteArrayBuffer.java:352)W / System.err:在android.mobile.historian.Data.Convert.intToBytes (Convert.java:136)

在调试模式下,我看到intBuffer的容量为4,这与我的Integer值所期望的一样。 那么,这里出了什么问题?

在此处输入图片说明

您在第二次运行该函数时会溢出全局缓冲区。

private static ByteBuffer intBuffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);

    public static byte[] intToBytes(int Value)
    {
        intBuffer.clear(); //THIS IS IMPORTANT, YOU NEED TO RESET THE BUFFER
        intBuffer.order(ByteOrder.LITTLE_ENDIAN);
        intBuffer.putInt(Value);
        return intBuffer.array();
    }

ByteBuffer.putInt()上的某些上下文:将给定的int写入当前位置,并将位置增加4。将int使用当前字节顺序转换为字节。 如果position大于limit-4,则抛出BufferOverflowException。如果不能对此缓冲区的内容进行任何更改,则抛出ReadOnlyBufferException。

您正在多次运行该功能。 每次运行函数时,都会在第一个整数之后将一个新的整数放入缓冲区。 但是,空间不足。 您需要在函数内部声明字节缓冲区。

您的代码第二次调用该方法时溢出。 这是因为您已为一个整数分配了足够的空间,但尚未重置缓冲区。 因此,当您第二次调用时,缓冲区已满,并且您会收到异常。

尝试这个:

public static byte[] intToBytes(int Value)
{
    intBuffer.clear();
    intBuffer.order(ByteOrder.LITTLE_ENDIAN);
    intBuffer.putInt(Value);
    return intBuffer.array();
}

旁注:我怀疑您需要缓存该对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM