Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Java Long to byte[] for Cassandra?

Tags:

java

cassandra

Lazy programmer alert. :)

Cassandra stores column values as bytes (Java example). Specifying a LongType comparator compares those bytes as a long. I want the value of a long into a Cassandra-friendly byte[]. How? I poked around for awhile. I think you people can help me faster.

EDIT:

Both Alexander and Eli's answers agreed with this reverse transformation. Thanks!

like image 713
dfrankow Avatar asked Dec 17 '22 01:12

dfrankow


1 Answers

I would write the long to a ByteArrayOutputStream wrapped in a DataOutputStream and then retrieve the raw bytes, although this will always give you your data in big endian byte order (most significant byte first):

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 be able to specify the 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();
}
like image 178
Eli Courtwright Avatar answered Dec 21 '22 11:12

Eli Courtwright