Java Array Shift shiftLeftAndFill(byte[] array, int positions)

Here you can find the source of shiftLeftAndFill(byte[] array, int positions)

Description

Shift byte array a certain number of positions to left (where the minus significant bit is at the right end), and fill with 0's as the array is moved.

License

Apache License

Parameter

Parameter Description
array a parameter
positions a parameter

Declaration

public final static byte[] shiftLeftAndFill(byte[] array, int positions) 

Method Source Code

//package com.java2s;
/*// w  ww.  ja va  2  s.c  om
 * Copyright Gradiant (http://www.gradiant.org) 2014
 * 
 * APACHE LICENSE v2.0
 * 
 * Author: Dr. Luis Rodero-Merino (lrodero@gradiant.org)
 */

public class Main {
    /**
     * Shift byte array a certain number of positions to left (where the minus significant bit is at the right end), and fill
     * with 0's as the array is moved. Up to 7 bits (positions) can be shifted.
     * @param array
     * @param positions
     * @return
     */
    public final static byte[] shiftLeftAndFill(byte[] array, int positions) {
        if (array == null)
            throw new IllegalArgumentException("Cannot shift a null byte array");
        if (positions < 0)
            throw new IllegalArgumentException("Cannot shift a negative number of positions");
        if (positions >= 8)
            throw new IllegalArgumentException(
                    "Weird error, should not be asking for shifting more than 7 positions, but " + positions
                            + " are asked for");
        byte[] result = new byte[array.length];
        byte mask = (byte) (((byte) 0xff) << (8 - positions));
        for (int i = array.length - 1; i >= 0; i--) { // Traversing array from left to right
            result[i] = (byte) (array[i] << positions);
            if (i == 0) {
                break;
            }
            // 'Retrieving' bits from following byte at the right, so they are not lost
            byte fromFoll = (byte) (array[i - 1] & mask);
            fromFoll = (byte) ((fromFoll & 0xff) >>> (8 - positions)); // The 0xff mask is to prevent the '>>>' operator to make appear some 1's...
            result[i] = (byte) (result[i] | fromFoll);
        }
        return result;
    }
}

Related

  1. shiftLeft(byte[] data, int shiftBy)
  2. shiftLeft(Object[] arr, int startIndex, int endIndex)
  3. shiftLeft(Object[] array, int amount)
  4. shiftLeft(Object[] object)
  5. shiftLeft1(T[] array)
  6. shiftLeftByCopying(int[] table, int shift)
  7. shiftLeftByOne(int[] table)
  8. shiftLeftI(long[] v, int off)
  9. ShiftLeftOne(int[] arr)