Java Byte Array Create toByteArray(boolean[] bits)

Here you can find the source of toByteArray(boolean[] bits)

Description

to Byte Array

License

Apache License

Declaration

static public byte[] toByteArray(boolean[] bits) 

Method Source Code

//package com.java2s;
/*//from w  w  w  .  j  a  va 2 s  .c  o  m
 * Copyright (C) 2016 "Invertor" Factory", JSC
 * [http://www.sbp-invertor.ru]
 *
 * This file is part of JLibModbus.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Authors: Vladislav Y. Kochedykov, software engineer.
 * email: vladislav.kochedykov@gmail.com
 */

public class Main {
    static public byte[] toByteArray(boolean[] bits) {
        byte[] dst = new byte[(int) Math.ceil((double) bits.length / 8)];
        for (int i = 0; i < bits.length; i++) {
            dst[i / 8] |= (byte) ((bits[i] ? 1 : 0) << (i % 8));
        }
        return dst;
    }

    static public byte[] toByteArray(int[] i16) {
        byte[] dst = new byte[i16.length * 2];
        for (int i = 0, j = 0; i < i16.length; i++, j += 2) {
            dst[j] = (byte) ((i16[i] >> 8) & 0xff);
            dst[j + 1] = (byte) (i16[i] & 0xff);
        }
        return dst;
    }

    static public byte[] toByteArray(short[] src) {
        byte[] dst = new byte[src.length];
        for (int i = 0; i < src.length; i++)
            dst[i] = (byte) src[i];
        return dst;
    }

    public static byte[] toByteArray(short i16) {
        return new byte[] { byteHigh(i16), byteLow(i16) };
    }

    public static byte[] toByteArray(int i32) {
        byte[] regs = new byte[4];
        regs[0] = (byte) (0xff & (i32 >> 8));
        regs[1] = (byte) (0xff & i32);
        regs[2] = (byte) (0xff & (i32 >> 24));
        regs[3] = (byte) (0xff & (i32 >> 16));
        return regs;
    }

    public static byte[] toByteArray(float f32) {
        return toByteArray(Float.floatToIntBits(f32));
    }

    public static byte byteHigh(int b) {
        return (byte) (((short) b >> 8) & 0xff);
    }

    public static byte byteLow(int b) {
        return (byte) ((short) b & 0xff);
    }
}

Related

  1. newByteArray(int... bytes)
  2. newByteArray(int... bytes)
  3. toByte(char[] bytes, boolean le)
  4. toByteArr(final float value, final boolean lsbIsFirst)
  5. toByteArray(boolean[] array)
  6. toByteArray(byte arg, int length)
  7. toByteArray(byte b)
  8. toByteArray(byte byteArray)
  9. toByteArray(byte num)