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!
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With