开发者

How to convert a byte array to two long values?

开发者 https://www.devze.com 2023-02-06 06:28 出处:网络
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?

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.BufferUnderflowExce开发者_运维百科ption
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();


You can do

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


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

精彩评论

暂无评论...
验证码 换一张
取 消