如何将字节数组转换为两个长值?

时间:2011-01-22 00:19:04

标签: java arrays type-conversion bytebuffer bufferunderflowexception

我正在使用byte[16]从JDBC ResultSet读取一个16字节数组(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();

4 个答案:

答案 0 :(得分:4)

你可以做到

ByteBuffer buffer = ByteBuffer.wrap(bytes);
long leastSignificant = buffer.getLong(); 
long mostSignificant = buffer.getLong(); 

答案 1 :(得分:2)

在将字节插入其中后,必须使用ByteBuffer方法重置flip()(从而允许getLong()调用从start开始读取 - offset 0):

buffer.put(bytes);     // Note: no reassignment either

buffer.flip();

long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();

答案 2 :(得分:1)

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);

答案 3 :(得分:1)

试试这个:

LongBuffer buf = ByteBuffer.wrap(bytes).asLongBuffer();
long l1 = buf.get();
long l2 = buf.get();