How to convert a byte array to two long values?

4.5k views Asked by At

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

There are 4 answers

0
Peter Lawrey On BEST ANSWER

You can do

ByteBuffer buffer = ByteBuffer.wrap(bytes);
long leastSignificant = buffer.getLong(); 
long mostSignificant = buffer.getLong(); 
0
Subtle Fox On

Try this:

LongBuffer buf = ByteBuffer.wrap(bytes).asLongBuffer();
long l1 = buf.get();
long l2 = buf.get();
0
Yuval Rimar On
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);
0
trojanfoe On

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