Java Binary Encode toBinaryString(byte[] bytes)

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

Description

Translate the given byte array into a string of 1s and 0s

License

Apache License

Parameter

Parameter Description
bytes The bytes to translate

Return

The string

Declaration

public static String toBinaryString(byte[] bytes) 

Method Source Code

//package com.java2s;
/*/*  ww  w. j av  a  2s.  c om*/
 * Copyright 2008-2013 LinkedIn, Inc
 *
 * 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 {
    /**
     * Translate the given byte array into a string of 1s and 0s
     *
     * @param bytes The bytes to translate
     * @return The string
     */
    public static String toBinaryString(byte[] bytes) {
        StringBuilder buffer = new StringBuilder();
        for (byte b : bytes) {
            String bin = Integer.toBinaryString(0xFF & b);
            bin = bin.substring(0, Math.min(bin.length(), 8));

            for (int j = 0; j < 8 - bin.length(); j++) {
                buffer.append('0');
            }

            buffer.append(bin);
        }
        return buffer.toString();
    }
}

Related

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