Convert a boolean array into a byte. - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Convert a boolean array into a byte.

Demo Code


//package com.java2s;

public class Main {
    /**/* w w w.  j a  v  a 2s .c  o  m*/
     * Converys a boolean array into a byte. Each boolean refers to a different digit in the byte's binary. For example, a boolean
     * array of [true, true, true, false, false, false, true, false] would return a byte with the binary makeup of 11100010. (Or -98)
     * @param a - The boolean array to convert. Must be a length of at least 8.
     * @return The byte.
     */
    public static byte fromBooleanArray(boolean[] a) {
        byte b = 0;
        if (a[7])
            b += 1;
        if (a[6])
            b += 2;
        if (a[5])
            b += 4;
        if (a[4])
            b += 8;
        if (a[3])
            b += 16;
        if (a[2])
            b += 32;
        if (a[1])
            b += 64;
        if (a[0])
            b += 128;
        return b;
    }
}

Related Tutorials