Java Binary to Char binaryToChar(char[] binaryStr, int charLen)

Here you can find the source of binaryToChar(char[] binaryStr, int charLen)

Description

binary To Char

License

Apache License

Declaration

private static char[] binaryToChar(char[] binaryStr, int charLen) 

Method Source Code

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

public class Main {

    private static char[] binaryToChar(char[] binaryStr, int charLen) {
        int len = binaryStr.length;
        int num = 0;
        if (len % charLen == 0)
            num = len / charLen;/*from  w  w  w. j  a  v  a2  s.  co  m*/
        else
            num = len / charLen + 1;

        char[] values = new char[num];

        int end = len - 1;
        for (int pos = num - 1; pos >= 0; pos--) {
            values[pos] = getCharDigit(binaryStr,
                    end - charLen + 1 >= 0 ? end - charLen + 1 : 0, end);
            end -= charLen;
        }
        return values;
    }

    private static char getCharDigit(char[] binaryStr, int start, int end) {
        int sum = 0;
        int multiplier = 1;
        for (int index = end; index >= start; index--) {
            if (binaryStr[index] == '1')
                sum += multiplier;
            multiplier *= 2;
        }
        if (sum < 10)
            return (char) ('0' + sum);
        else
            return (char) ('a' + sum - 10);
    }
}

Related

  1. BinaryToAscii(String binary)
  2. binaryToCharacter(String s)