質問

バイナリデータを含む文字列(1110100)があります。テキストを取得して印刷できるようにしたいと思います(1110100は「t」を印刷します)。これを試してみました。テキストをバイナリに変換するために使用したものと似ていますが、まったく機能しません。

    public static String toText(String info)throws UnsupportedEncodingException{
        byte[] encoded = info.getBytes();
        String text = new String(encoded, "UTF-8");
        System.out.println("print: "+text);
        return text;
    }

修正や提案がございましたら、よろしくお願いいたします。

ありがとう!

役に立ちましたか?

解決

使用できます Integer.parseInt バイナリ文字列を整数に変換するには、基数 2 (バイナリ) を使用します。

int charCode = Integer.parseInt(info, 2);

次に、対応する文字を文字列として必要な場合は、次のようにします。

String str = new Character((char)charCode).toString();

他のヒント

OPではバイナリが String 形式ですが、完全を期すために、形式から直接変換するソリューションを追加しようと思いました。 byte[] アルファベットの文字列表現に変換します。

として カサブランカ 基本的にはアルファベットの数値表現を取得する必要があると述べました。1 文字より長いものを変換しようとしている場合は、おそらく次のようになります。 byte[] それを文字列に変換し、for ループを使用してそれぞれの文字を追加する代わりに、 byte 使用できます バイトバッファ そして 文字バッファ あなたに代わってリフティングを行うには:

public static String bytesToAlphabeticString(byte[] bytes) {
    CharBuffer cb = ByteBuffer.wrap(bytes).asCharBuffer();
    return cb.toString();
}

注:UTF文字セットを使用します

あるいは、String コンストラクターを使用します。

String text = new String(bytes, 0, bytes.length, "ASCII");

これは私の1(のJava 8での作業罰金)です。

String input = "01110100"; // Binary input as String
StringBuilder sb = new StringBuilder(); // Some place to store the chars

Arrays.stream( // Create a Stream
    input.split("(?<=\\G.{8})") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte)
).forEach(s -> // Go through each 8-char-section...
    sb.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
);

String output = sb.toString(); // Output text (t)

とコンソールに印刷圧縮方法:

Arrays.stream(input.split("(?<=\\G.{8})")).forEach(s -> System.out.print((char) Integer.parseInt(s, 2))); 
System.out.print('\n');

私はこれを行うには、「より良い」の方法があるが、これはあなたがおそらく得ることができる最小のものであると確信しています。

ここで答えがある。

private String[] splitByNumber(String s, int size) {
    return s.split("(?<=\\G.{"+size+"})");
}
周り

他の方法

(「情報」は、入力されたテキストおよび「S」、それのバイナリバージョンです)
byte[] bytes = info.getBytes();
BigInteger bi = new BigInteger(bytes);
String s = bi.toString(2); 

見てください parseInt 関数。キャストや Character.toString 関数。

public static String binaryToText(String binary) {
    return Arrays.stream(binary.split("(?<=\\G.{8})"))/* regex to split the bits array by 8*/
                 .parallel()
                 .map(eightBits -> (char)Integer.parseInt(eightBits, 2))
                 .collect(
                                 StringBuilder::new,
                                 StringBuilder::append,
                                 StringBuilder::append
                 ).toString();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top