如何将Java Long转换为Cassandra的byte []? [英] How to convert a Java Long to byte[] for Cassandra?

查看:145
本文介绍了如何将Java Long转换为Cassandra的byte []?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

懒惰的程序员警报。 :)

Lazy programmer alert. :)

Cassandra将列值存储为字节( Java示例)。指定 LongType比较器会将这些字节作为长整型。我想要一个长的值到Cassandra友好的字节[]。怎么样?我戳了一会儿。我认为你的人可以帮助我更快。

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.

编辑:

Eli的回答符合这个反向变换。谢谢!

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

推荐答案

这里是从Java 6剪切和粘贴 DataOutputStream.writeLong

Here is cut and paste 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);
}

这里是您的情况的修改

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;
}

这篇关于如何将Java Long转换为Cassandra的byte []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆