Java Binary Encode toBinaryString(byte[] bytes)

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

Description

Converts byte array to a binary String by MSB order.

License

Apache License

Parameter

Parameter Description
bytes a byte array

Return

binary String

Declaration

public static String toBinaryString(byte[] bytes) 

Method Source Code

//package com.java2s;
/**/*from  w w w. j  a  v  a2 s .com*/
 *
 * @author Wei-Ming Wu
 *
 *
 * Copyright 2013 Wei-Ming Wu
 *
 * 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.
 *
 */

public class Main {
    /**
     * Converts byte array to a binary String by MSB order.
     * 
     * @param bytes
     *          a byte array
     * @return binary String
     */
    public static String toBinaryString(byte[] bytes) {
        return toBinaryString(bytes, true);
    }

    /**
     * Converts a byte array to a binary String.
     * 
     * @param bytes
     *          a byte array
     * @param isMSB
     *          true if MSB, false if LSB
     * @return binary String
     */
    public static String toBinaryString(byte[] bytes, boolean isMSB) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String binary = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
            if (isMSB)
                sb.append(binary);
            else
                sb.append(new StringBuilder(binary).reverse());
        }
        return sb.toString();
    }

    /**
     * Reverses a byte array in place.
     * 
     * @param bytes
     *          to be reversed
     */
    public static void reverse(byte[] bytes) {
        for (int i = 0; i < bytes.length / 2; i++) {
            byte temp = bytes[i];
            bytes[i] = bytes[bytes.length - 1 - i];
            bytes[bytes.length - 1 - i] = temp;
        }
    }
}

Related

  1. toBinaryString(byte b)
  2. toBinaryString(byte b)
  3. toBinaryString(byte... bytes)
  4. toBinaryString(byte[] array)
  5. toBinaryString(byte[] bytes)
  6. toBinaryString(byte[] bytes, int bitSize)
  7. toBinaryString(byte[] data, boolean format)
  8. toBinaryString(char value)
  9. toBinaryString(final boolean[] bits)