Java Base2 Encode toBase2(int[] arr)

Here you can find the source of toBase2(int[] arr)

Description

to Base

License

Apache License

Declaration

public static String toBase2(int[] arr) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String toBase2(int[] arr) {

        if (arr == null) {
            return "";
        }//from w w w  .  ja  va 2  s.com

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < arr.length; i++) {
            sb.append(toBase2(arr[i]));

            if (i < arr.length - 1) {
                sb.append(" ");
            }
        }

        return sb.toString();
    }

    public static String toBase2(int b) {

        if (b > 0xff) {
            throw new IllegalArgumentException(String.format("Input value [%1$s] is larger than a byte", b));
        }

        return padBase2(Integer.toBinaryString(b));
    }

    /**
     * Converts an int array to string.  
     * Note: this method does not validate that int values map
     * to valid characters
     * 
     * @param arr
     * @return
     */
    public static String toString(int[] arr) {

        if (arr == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();

        for (int anArr : arr) {
            sb.append((char) anArr);
        }

        return sb.toString();
    }

    private static String padBase2(String s) {

        for (int i = s.length(); i < 8; i++) {
            s = "0" + s;
        }

        return s;
    }
}

Related

  1. toBase2(int b)
  2. toBase2(int decimalNumber)