バイト配列を2つの長い値に変換する方法は?
-
16-10-2019 - |
質問
私は16バイトの配列を読んでいます(byte[16]
)JDBCから ResultSet
と rs.getBytes("id")
そして今、私はそれを2つの長い値に変換する必要があります。どうやってやるの?
これは私が試したコードですが、おそらく使用しなかった 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();
他のヒント
リセットする必要があります ByteBuffer
を使用して flip()
方法バイトを挿入した後(それにより、getlong()呼び出しが開始から読み取ることを許可します - オフセット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);
これを試して:
LongBuffer buf = ByteBuffer.wrap(bytes).asLongBuffer();
long l1 = buf.get();
long l2 = buf.get();
所属していません StackOverflow