如何将字节数组转换为两个长值?
-
16-10-2019 - |
题
我正在阅读16个字节阵列(byte[16]
)来自JDBC ResultSet
和 rs.getBytes("id")
现在,我需要将其转换为两个长值。我怎样才能做到这一点?
这是我尝试过的代码,但我可能没有使用 ByteBuffer
正确。
byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);
// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
我使用以下方式将字节数组存储到数据库中
byte[] bytes = ByteBuffer.allocate(16)
.putLong(leastSignificant)
.putLong(mostSignificant).array();
解决方案
你可以做
ByteBuffer buffer = ByteBuffer.wrap(bytes);
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
其他提示
你必须重置 ByteBuffer
使用 flip()
方法将字节插入其中之后(从而允许从开始 - 偏移0)读取getlong()调用):
buffer.put(bytes); // Note: no reassignment either
buffer.flip();
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
long getLong(byte[] b, int off) {
return ((b[off + 7] & 0xFFL) << 0) +
((b[off + 6] & 0xFFL) << 8) +
((b[off + 5] & 0xFFL) << 16) +
((b[off + 4] & 0xFFL) << 24) +
((b[off + 3] & 0xFFL) << 32) +
((b[off + 2] & 0xFFL) << 40) +
((b[off + 1] & 0xFFL) << 48) +
(((long) b[off + 0]) << 56);
}
long leastSignificant = getLong(bytes, 0);
long mostSignificant = getLong(bytes, 8);
尝试这个:
LongBuffer buf = ByteBuffer.wrap(bytes).asLongBuffer();
long l1 = buf.get();
long l2 = buf.get();
不隶属于 StackOverflow