Java ByteBuffer Shift leftShift(final ByteBuffer buffer, int shift)

Here you can find the source of leftShift(final ByteBuffer buffer, int shift)

Description

left Shift

License

Apache License

Declaration

public static ByteBuffer leftShift(final ByteBuffer buffer, int shift) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
    private static final byte BYTE_LENGTH = 8;

    public static ByteBuffer leftShift(final ByteBuffer buffer, int shift) {
        final BigInteger bigInt = new BigInteger(buffer.array());
        final byte[] shiftedBytes = bigInt.shiftLeft(shift).and(allOnes((buffer.remaining()) * BYTE_LENGTH))
                .toByteArray();/*from  w  ww .j av  a 2 s  . co m*/
        final int resultLength = buffer.capacity();
        final int sourceOffset = resultLength >= shiftedBytes.length ? 0 : 1;
        final int destinationOffset = resultLength - shiftedBytes.length > 0 ? resultLength - shiftedBytes.length
                : 0;
        Arrays.fill(buffer.array(), (byte) 0);
        System.arraycopy(shiftedBytes, sourceOffset, buffer.array(), destinationOffset,
                shiftedBytes.length - sourceOffset);
        return buffer;
    }

    private static BigInteger allOnes(final int length) {
        return BigInteger.ZERO.setBit(length).subtract(BigInteger.ONE);
    }
}

Related

  1. shift(ByteBuffer buffer, int distance)