如何将Java Long转换为Cassandra的byte []?

dfr*_*kow 4 java cassandra

懒惰的程序员警报.:)

Cassandra将列值存储为字节(Java示例).指定LongType比较器将这些字节比较为long.我希望long的值成为一个Cassandra友好的byte [].怎么样?我捅了一会儿.我想你们人们可以更快地帮助我.

编辑:

Alexander和Eli的回答都同意这种逆向转换.谢谢!

Eli*_*ght 5

我会将long写入包含在DataOutputStream中ByteArrayOutputStream,然后检索原始字节,尽管这将始终以big endian字节顺序(最重要的字节优先)提供给你的数据:

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

如果您希望能够指定字节顺序,可以使用ByteBuffer类:

public static byte[] getBytes(Long val)
{
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(val);
    return buf.array();
}
Run Code Online (Sandbox Code Playgroud)