Extracts the least significant bits from a byte array and creates a byte[] with values - Java java.lang

Java examples for java.lang:byte Array Bit Operation

Description

Extracts the least significant bits from a byte array and creates a byte[] with values

Demo Code


//package com.java2s;

public class Main {
    /**// w  w w. j  a v a2s . c o m
     * Extracts the least significant bits from a byte array and creates a byte[] with values
     * @param byteArray The byte array to extract from
     * @return A new byte[] containing all the least significant bits
     */
    public static byte[] extractLsbFromByteArray(byte[] byteArray) {

        byte[] lsbByteArray = new byte[byteArray.length / Byte.SIZE];

        int count = 1;
        byte lsbByte = 0;
        int finalByteArrayPos = 0;

        // loop through the byte array
        for (int i = 0; i < byteArray.length; i++) {
            int byteValue = byteArray[i];

            // get the least signiciant value
            boolean value = (Integer.lowestOneBit(byteValue) == 1);
            // set the byte
            if (value)
                lsbByte |= (1 << (Byte.SIZE - count));

            lsbByteArray[finalByteArrayPos] = lsbByte;

            // if size of byte then reset value and increment position
            if (count == Byte.SIZE) {
                lsbByte = 0;
                count = 0;
                finalByteArrayPos++;
            }
            count++;
        }

        return lsbByteArray;
    }
}

Related Tutorials