如何将位数组转换为文本

时间:2014-05-01 09:09:56

标签: java arrays text bits

我有一个字符串,例如" java education"我把它转换成了比特。现在我有一个位数组。我想将它转换回文本。怎么做?

String s="Java Education";
char[] ch=s.toCharArray();
String g="  ";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
    g=Integer.toBinaryString((int)c);
    sb.append(ch);
}
char[] ch2= sb.toString.toCharArray();

我想从数组ch2中取回文本。

2 个答案:

答案 0 :(得分:0)

试试这个

import java.util.Arrays;

public class DecodeBits {

    public static void main(String[] args) {
        String s = "Java Education";
        char[] ch = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char c : ch) {
            // Wen need a fix length
            String g = String.format("%16s", Integer.toBinaryString((int) c)).replace(' ', '0');
            // this seems to be typo
            // sb.append(ch);
            sb.append(g);
        }
        char[] ch2 = sb.toString().toCharArray();
        int start = 0;
        while (start < ch2.length - 15) {
            char[] bits = Arrays.copyOfRange(ch2, start, start + 16);
            int cValue = Integer.parseInt(new String(bits), 2);
            char[] chars = Character.toChars(cValue);
            System.out.print(chars[0]);
            start += 16;

        }
        System.out.println("");
    }
}

答案 1 :(得分:0)

这是我的实施:

    String s="Java Education";
    char[] ch=s.toCharArray();
    String g="";
    StringBuilder sb= new StringBuilder();
    for(char c:ch)
    {
        g=Integer.toBinaryString((int)c);
        if(g.length()<8){
            for(int h=0; h<8-g.length(); h++){
                g="0"+g;
            }
        }
        sb.append(g);
        sb.append(',');
    }
    char[] ch2= sb.toString().toCharArray();
    String[] s3 = new String(ch2).split(",");

    for(String t: s3){
        String d="";
        for(int x=t.length()-1; x>=0; x--) d+=t.charAt(x);
        t=d;
        int num=0;
        for(int j=0; j<t.length(); j++){
            num+=Integer.parseInt(""+t.charAt(j))*Math.pow(2, j);
        }
        System.out.print((char)num);
    }