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

后端 未结 4 1709
时光取名叫无心
时光取名叫无心 2021-01-01 03:58

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

相关标签:
4条回答
  • 2021-01-01 04:26

    You can crack the bytes apart by using shifts and mask, or a bit easier is ByteBuffer.wrap to wrap an 8 long byte array and using the putLong method. You must set the ByteOrder first using the ByteBuffer.order method.

    0 讨论(0)
  • 2021-01-01 04:28

    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();
    }
    
    0 讨论(0)
  • 2021-01-01 04:30

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

    Here are modifications 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;
    }
    
    0 讨论(0)
  • 2021-01-01 04:40

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

    0 讨论(0)
提交回复
热议问题