如何将字节数组转换为两个长整型值?
问题描述:
我正在读取一个来自JDBC ResultSet
与rs.getBytes("id")
的16字节数组(byte[16]
),现在我需要将它转换为两个长整型值。我怎样才能做到这一点?如何将字节数组转换为两个长整型值?
这是我试过的代码,但我可能没有正确使用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();
答
您可以选择使用flip()
方法插入字节后进去(从而使getLong()调用重置ByteBuffer
从一开始读 - 偏移0):
buffer.put(bytes); // Note: no reassignment either
buffer.flip();
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
+0
谢谢,工作完美。 – Jonas 2011-01-22 00:34:41
答
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();
+1啊,这更美丽。谢谢。 – Jonas 2011-02-05 07:20:23