Question

I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

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

I stored the byte array to the database using:

byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();
Was it helpful?

Solution

You can do

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

OTHER TIPS

You have to reset the ByteBuffer using the flip() method after you insert the bytes into it (thereby allowing the getLong() calls to read from the start - offset 0):

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

Try this:

LongBuffer buf = ByteBuffer.wrap(bytes).asLongBuffer();
long l1 = buf.get();
long l2 = buf.get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top