Android ByteBuffer to Long Convert writeVLong(ByteBuffer out, long i)

Here you can find the source of writeVLong(ByteBuffer out, long i)

Description

Similar to WritableUtils#writeVLong(java.io.DataOutput,long) , but writes to a ByteBuffer .

License

Apache License

Declaration

public static void writeVLong(ByteBuffer out, long i) 

Method Source Code

//package com.java2s;
/*//from  www .  j  av a 2s  . c  om
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Similar to {@link WritableUtils#writeVLong(java.io.DataOutput, long)},
     * but writes to a {@link ByteBuffer}.
     */
    public static void writeVLong(ByteBuffer out, long i) {
        if (i >= -112 && i <= 127) {
            out.put((byte) i);
            return;
        }

        int len = -112;
        if (i < 0) {
            i ^= -1L; // take one's complement
            len = -120;
        }

        long tmp = i;
        while (tmp != 0) {
            tmp = tmp >> 8;
            len--;
        }

        out.put((byte) len);

        len = (len < -120) ? -(len + 120) : -(len + 112);

        for (int idx = len; idx != 0; idx--) {
            int shiftbits = (idx - 1) * 8;
            long mask = 0xFFL << shiftbits;
            out.put((byte) ((i & mask) >> shiftbits));
        }
    }
}

Related

  1. readLong(ByteBuffer in, final int fitInBytes)