Java Binary to Char binaryToCharacter(String s)

Here you can find the source of binaryToCharacter(String s)

Description

Translates a byte (representing one character) to its character representation.

License

Open Source License

Parameter

Parameter Description
s The binary sequence representing a single character.

Return

The character corresponding to the given binary-sequence.

Declaration

private static char binaryToCharacter(String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static final int LENGTH_OF_BINARY_UNIT = 8;
    public static final int BASE_OF_BINARY_UNIT = 2;
    public static final int MAX_EXPONENT_IN_BINARY_UNIT = 7;

    /**//w  ww  .  ja  v  a  2 s . c  o m
     * Translates a byte (representing one character) to its character representation.
     * A newly defined char-array gets the converted input-String.
     * Each bit is multiplied with its position-value. The sum of those values is the decimal 
     * value of the character.
     * 
     * @param s      The binary sequence representing a single character.
     * 
     * @return      The character corresponding to the given binary-sequence.
     */
    private static char binaryToCharacter(String s) {
        char[] binaryCharacter = s.toCharArray();
        int decimalValueOfCharacter = 0;

        for (int i = 0; i < LENGTH_OF_BINARY_UNIT; i++) {
            double bitPositionValue = Math.pow(BASE_OF_BINARY_UNIT,
                    (MAX_EXPONENT_IN_BINARY_UNIT - i));
            decimalValueOfCharacter += (binaryCharacter[i] - '0')
                    * Math.round(bitPositionValue);
        }

        return (char) decimalValueOfCharacter;
    }
}

Related

  1. BinaryToAscii(String binary)
  2. binaryToChar(char[] binaryStr, int charLen)