Java Byte Array Create toBytes(boolean[] input)

Here you can find the source of toBytes(boolean[] input)

Description

Returns a byte array transformed from the specified boolean array.

License

Open Source License

Parameter

Parameter Description
input the boolean array to transform to a byte array

Return

a byte array

Declaration

public static byte[] toBytes(boolean[] input) 

Method Source Code

//package com.java2s;
/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses///from   w ww  .ja v a 2s.  c  o  m
 * ---------------------------------------------------------------------
 */

public class Main {
    /**
     * Returns a byte array transformed from the specified boolean array.
     * @param input     the boolean array to transform to a byte array
     * @return          a byte array
     */
    public static byte[] toBytes(boolean[] input) {
        byte[] toReturn = new byte[input.length / 8];
        for (int entry = 0; entry < toReturn.length; entry++) {
            for (int bit = 0; bit < 8; bit++) {
                if (input[entry * 8 + bit]) {
                    toReturn[entry] |= (128 >> bit);
                }
            }
        }

        return toReturn;
    }
}

Related

  1. toByteArrayShifted2(int[][] intArray)
  2. ToByteArrayString(byte[] bytes)
  3. toByteArrayV4(String address)
  4. toByteArrayV6(String address)
  5. toByteInfo(long bytes)
  6. toBytes(byte data)
  7. toBytes(byte[] b, int offset, long val)
  8. toBytes(byte[] buffer, int pos, String string)
  9. toBytes(byte[] ipAddress, int port)