public ByteBuffer toByteBuffer() {
        ByteBuffer buf;

        long cardinality = getLongCardinality();
        if (cardinality <= 32L) {
            buf = newBuffer(2 + byteLen * (int) cardinality);
            buf.put((byte) 0);
            buf.put((byte) cardinality);
            if (byteLen == 1) {
                for (int v : toIntArray()) {
                    buf.put((byte) v);
                }
            } else if (byteLen == 2) {
                for (int v : toIntArray()) {
                    buf.putShort((short) v);
                }
            } else if (byteLen == 4) {
                for (int v : toIntArray()) {
                    buf.putInt(v);
                }
            } else { // 64
                for (long v : toLongArray()) {
                    buf.putLong(v);
                }
            }
        } else if (byteLen <= 4) {
            int size = serializedSizeInBytes();
            int varIntSize = ClickHouseByteUtils.getVarIntSize(size);

            buf = newBuffer(1 + varIntSize + size);
            buf.put((byte) 1);
            ClickHouseByteUtils.setVarInt(buf, size);
            serialize(buf);
        } else { // 64
            long size = serializedSizeInBytesAsLong();
            int varIntSize = ClickHouseByteUtils.getVarLongSize(size);
            // TODO add serialize(DataOutput) to handle more
            int intSize = (int) size;
            buf = newBuffer(1 + varIntSize + intSize);
            buf.put((byte) 1);
            ClickHouseByteUtils.setVarInt(buf, intSize);
            serialize(buf);
        }

        return (ByteBuffer) ((Buffer) buf).flip();
    }
Serialize the bitmap into a flipped ByteBuffer.

@return flipped byte buffer
clickhouse-data/src/main/java/com/clickhouse/data/value/ClickHouseBitmap.java