Java Binary Encode toBinary(final byte[] bytes)

Here you can find the source of toBinary(final byte[] bytes)

Description

Turn a byte array into 1's and 0's (in a String)

License

Mozilla Public License

Parameter

Parameter Description
bytes byte[] array

Return

binary as a String

Declaration

public static String toBinary(final byte[] bytes) 

Method Source Code

//package com.java2s;
/*//  w  w w .  ja  v a 2s .  c o  m
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

public class Main {
    /**
     * Turn a byte array into 1's and 0's (in a String)
     *
     * @param bytes byte[] array
     * @return binary as a String
     */
    public static String toBinary(final byte[] bytes) {
        final StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
        for (int i = 0; i < Byte.SIZE * bytes.length; i++) {
            sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
        }
        return sb.toString();
    }
}

Related

  1. toBinary(byte b)
  2. toBinary(byte b)
  3. toBinary(byte b)
  4. toBinary(byte[] bytes)
  5. toBinary(final byte[] array, final int offset, final int length)
  6. toBinary(final double d)
  7. toBinary(final double d)
  8. toBinary(final Object o)
  9. toBinary(int nr, int bits)