将二进制数组转换为Char Java

时间:2016-07-30 20:56:40

标签: java arrays string char int

我有这个二进制数组:

int[] bitArray = {
    0,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,0,1,1,
    0,1,1,1,0,1,0,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,1,
    0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,1,0,1,0,0,
    0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,0,1,1,0,1,1,0,1,0,1,1,
    0,1,1,1,1,0,0,1,};

它使短语:太阳在天空中 您如何将int二进制数组转换为char

3 个答案:

答案 0 :(得分:3)

每八位组成一个字符。你可以循环遍历这些位并将每八个累加在一起:

int[] bitArray = {0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1,};
char[] chars = new char[bitArray.length / 8];
for (int i = 0; i < chars.length; ++i) {
    int c = 0;
    for (int j = i * 8; j < (i + 1) * 8; ++j) {
        c = c << 1;
        c += bitArray[j];
    }
    chars[i] = (char)c;
}

String s = new String(chars);
System.out.println(s);

答案 1 :(得分:2)

循环遍历数组的每个字节(8位),创建这些位的字符串,然后使用Integer.parseInt(x,2)将这些位转换为整数,然后将其转换为字符并添加到结果

  public static void main (String[] args) throws java.lang.Exception
    {
        int[] bitArray = {0,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,0,1,1,0,1,1,1,0,1,0,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,0,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,0,0,1,};

         int CHAR_SIZE = 8;

         String T = "";
         String result ="";
         for (int i=0; i<bitArray.length; i+= CHAR_SIZE)
            {
                for (int j=0; j<CHAR_SIZE; j++)
                    T += Integer.toString(bitArray[i+j]);

                result += Character.toString((char)Integer.parseInt(T, 2));
                T="";
            }

            System.out.println(result);

    }

输出

The sun is in the sky

答案 2 :(得分:1)

ASCII字符是一个字节。一个字节是8位。将数组元素分成8(0-7),(8-15),......

的段

将这些细分存储在另一个数组中。使用以下构造函数完成。

public String(byte[] bytes, Charset charset)

请记住将utf8指定为您的字符集。这会导致将字符视为单字节ASCII字符。