How to convert Java Long to Byte [] for Cassandra?

Warning to a lazy programmer. :)

Cassandra stores column values ​​in bytes ( Java example ). Note The LongType compiler compares these bytes as long. I want the value to be in the Cassandra-friendly byte [] for a long time. How? I poked for a while. I think you people can help me faster.

EDIT:

Both the answers of Alexander and Eli agree with this inverse transformation . Thanks!

+4
source share
4 answers

Here is cut and pasted from java 6 DataOutputStream.writeLong

 public final void writeLong(long v) throws IOException { writeBuffer[0] = (byte)(v >>> 56); writeBuffer[1] = (byte)(v >>> 48); writeBuffer[2] = (byte)(v >>> 40); writeBuffer[3] = (byte)(v >>> 32); writeBuffer[4] = (byte)(v >>> 24); writeBuffer[5] = (byte)(v >>> 16); writeBuffer[6] = (byte)(v >>> 8); writeBuffer[7] = (byte)(v >>> 0); out.write(writeBuffer, 0, 8); incCount(8); } 

Here are the changes for your case.

 public final byte[] longToBytes(long v) { byte[] writeBuffer = new byte[ 8 ]; writeBuffer[0] = (byte)(v >>> 56); writeBuffer[1] = (byte)(v >>> 48); writeBuffer[2] = (byte)(v >>> 40); writeBuffer[3] = (byte)(v >>> 32); writeBuffer[4] = (byte)(v >>> 24); writeBuffer[5] = (byte)(v >>> 16); writeBuffer[6] = (byte)(v >>> 8); writeBuffer[7] = (byte)(v >>> 0); return writeBuffer; } 
+3
source

I would write a long ByteArrayOutputStream wrapped in a DataOutputStream and then retrieve the raw bytes, although this will always give you data in bytes of a large byte (the most significant byte):

 public static byte[] getBytes(Long val) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(val); return baos.toByteArray(); } 

If you want to specify endianness, you can use the ByteBuffer class:

 public static byte[] getBytes(Long val) { ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.BIG_ENDIAN); buf.putLong(val); return buf.array(); } 
+5
source

You can crack bytes with shifts and a mask, or a little easier ByteBuffer.wrap wrap 8 long ByteBuffer.wrap arrays and use the putLong method. You must first install ByteOrder using the ByteBuffer.order method.

+2
source

You can use the Cassandra utility class: ByteBufferUtil.bytes(long n)

+2
source

Source: https://habr.com/ru/post/1306976/


All Articles