简体   繁体   English

从较小的字节数组(Java)进行长时间转换

[英]Cast long from smaller byte array (Java)

I am trying to convert a byte array to long, but receive BufferUnderflowException 我正在尝试将字节数组转换为long,但是接收到BufferUnderflowException

    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    byte[] arg1 = new byte[] {0x04, (byte)0xB0};
    buffer.put(arg1, 0, arg1.length);
    buffer.flip();
    long val = buffer.getLong();

In debug mode, I looked inside buffer. 在调试模式下,我查看了缓冲区内部。 It has an internal byte array, and it fills the unspecified bytes with "0". 它具有一个内部字节数组,并且用“ 0”填充未指定的字节。 So why does the exception occur? 那么为什么会发生异常呢? How can I fix it? 我该如何解决?

The spec of getLong() specifically says that it throws BufferUnderflowException if there are fewer than eight bytes remaining in this buffer . getLong()规范专门指出,如果there are fewer than eight bytes remaining in this buffer ,它将引发BufferUnderflowException Your buffer has only two bytes. 您的缓冲区只有两个字节。

It seems like you should use Long.BYTES to fill your buffer . 似乎您应该使用Long.BYTES来填充buffer If your byte[] is exhausted you could switch to 0. Like, 如果您的byte[]已用尽,则可以切换为0。例如,

ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
byte[] arg1 = new byte[] { 0x04, (byte) 0xB0 };
for (int i = 0; i < Long.BYTES; i++) {
    int pos = Long.BYTES - i - 1;
    byte val = (pos < arg1.length) ? arg1[pos] : 0;
    buffer.put(val);
}
buffer.flip();
long val = buffer.getLong();
System.out.println(val);

Output is 输出是

45060

Going the other way 走另一条路

System.out.println(Integer.toHexString(45060));
b004

An ArrayList may have an Object[16] , but that still doesn't mean that its logical size is bigger than the number of elements you've added. ArrayList可能具有Object[16] ,但这仍然并不意味着其逻辑大小大于您添加的元素数。 You need eight bytes in the buffer to read a long out of it. 您需要在缓冲区八个字节读取long出来。

If you are trying to use that byte array as an unsigned short, just write leading zero bytes to the buffer. 如果尝试使用该字节数组作为无符号的short,只需将前导零字节写入缓冲区。 Not sure why you want a long over an int if it's just two bytes, though. 不知道为什么只需要两个字节就需要一个int整数。

The problem here is with -: buffer.flip(); 这里的问题是-: buffer.flip();

flip is used to flip the buffer from read to write mode or write to read mode by resetting the limit as the current position. flip用于将缓冲区从读取模式翻转到写入模式,或者通过将限制重置为当前位置来将其写入读取模式。

If you comment out the line, it will work fine. 如果您注释掉该行,它将正常工作。

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

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