Here you can find the source of shiftLeftAndFill(byte[] array, int positions)
Parameter | Description |
---|---|
array | a parameter |
positions | a parameter |
public final static byte[] shiftLeftAndFill(byte[] array, int positions)
//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; } }