Java - Write code to Convert byte array To String

Requirements

Write code to convert byte array To String

Convert each byte in the array to string

Hint

Use String.format() method to format the byte value

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        byte bytes = 42;
        System.out.println(bytesToString(bytes));
    }/*from  w  w w .ja v a 2 s . c  om*/

    public static String bytesToString(byte... bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte aByte : bytes) {
            String binStr = Integer.toBinaryString(aByte);
            int length = binStr.length();
            if (length > 8) {
                builder.append(binStr.substring(length - 8)).append(" ");
            } else {
                builder.append(
                        String.format("%08d", Integer.parseInt(binStr)))
                        .append(" ");
            }
        }
        return builder.toString();
    }
}

Related Exercise