Question

J'ai une chaîne avec des données binaires: (1110100) Je veux obtenir le texte sur je peux l'imprimer (1.110.100 imprimerait « t »). J'ai essayé, il est semblable à ce que je transformer mon texte en binaire, mais il ne fonctionne pas du tout:

    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;
    }

Les corrections ou suggestions seraient appréciés.

Merci!

Était-ce utile?

La solution

Vous pouvez utiliser Integer.parseInt avec une base de 2 (binaire) pour convertir la chaîne binaire à un nombre entier:

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

Ensuite, si vous voulez que le caractère correspondant comme une chaîne:

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

Autres conseils

Je sais que l'OP a déclaré que leur binaire était dans un format String mais pour être complet, je pensais que je voudrais ajouter une solution pour convertir directement à partir d'un byte[] à une représentation alphabétique String.

casablanca vous avez dit besoin essentiellement d'obtenir la représentation numérique du caractère alphabétique. Si vous essayez de convertir quoi que ce soit plus qu'un seul caractère, il viendra probablement en byte[] et au lieu de convertir que d'une chaîne, puis en utilisant une boucle pour ajouter les caractères de chaque byte vous pouvez utiliser ByteBuffer et CharBuffer pour faire la levée pour vous:

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

N.B.. Utilise ensemble UTF char

Vous pouvez également l'aide du constructeur String:

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

est mon (fonctionne bien sur 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)

et l'impression de procédé comprimé à la console:

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

Je suis sûr qu'il ya des « meilleurs » façons de le faire, mais c'est le plus petit que vous pouvez probablement obtenir.

Voici la réponse.

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

L'inverse (Où « info » est le texte d'entrée et « s » la version binaire de celui-ci)

byte[] bytes = info.getBytes();
BigInteger bi = new BigInteger(bytes);
String s = bi.toString(2); 

Regardez le parseInt fonction . Vous pouvez aussi avoir besoin d'un casting et Character.toString fonction .

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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top