Java 中的二进制到文本

发布于 2024-10-03 14:30:18 字数 405 浏览 5 评论 0原文

我有一个包含二进制数据的字符串(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;
    }

任何更正或建议将不胜感激。

谢谢!

I have a String with binary data in it (1110100) I want to get the text out so I can print it (1110100 would print "t"). I tried this, it is similar to what I used to transform my text to binary but it's not working at all:

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

Any corrections or suggestions would be much appreciated.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

等你爱我 2024-10-10 14:30:18

您可以使用 Integer.parseInt 以2(二进制)为基数将二进制字符串转换为整数:

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

那么如果你想要对应的字符作为字符串:

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

You can use Integer.parseInt with a radix of 2 (binary) to convert the binary string to an integer:

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

Then if you want the corresponding character as a string:

String str = new Character((char)charCode).toString();
太傻旳人生 2024-10-10 14:30:18

这是我的一个(在 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');

我确信有“更好”的方法可以做到这一点,但这是您可能得到的最小的方法。

This is my one (Working fine on 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)

and the compressed method printing to console:

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

I am sure there are "better" ways to do this but this is the smallest one you can probably get.

雨轻弹 2024-10-10 14:30:18

我知道OP声明他们的二进制文件是String格式,但为了完整性,我想我会添加一个解决方案来直接从byte[]转换为字母字符串表示形式。

正如casablanca所说,你基本上需要获得字母字符的数字表示。如果您尝试转换任何长于单个字符的内容,它可能会以 byte[] 形式出现,而不是将其转换为字符串,然后使用 for 循环附加每个 的字符>byte 您可以使用 ByteBufferCharBuffer 为您做提升:

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

NB 使用 UTF 字符集

或者使用 String 构造函数:

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

I know the OP stated that their binary was in a String format but for the sake of completeness I thought I would add a solution to convert directly from a byte[] to an alphabetic String representation.

As casablanca stated you basically need to obtain the numerical representation of the alphabetic character. If you are trying to convert anything longer than a single character it will probably come as a byte[] and instead of converting that to a string and then using a for loop to append the characters of each byte you can use ByteBuffer and CharBuffer to do the lifting for you:

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

N.B. Uses UTF char set

Alternatively using the String constructor:

String text = new String(bytes, 0, bytes.length, "ASCII");
七禾 2024-10-10 14:30:18
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();
}
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();
}
哥,最终变帅啦 2024-10-10 14:30:18

这就是答案。

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

Here is the answer.

private String[] splitByNumber(String s, int size) {
    return s.split("(?<=\\G.{"+size+"})");
}
彼岸花ソ最美的依靠 2024-10-10 14:30:18

相反(其中“info”是输入文本,“s”是它的二进制版本)

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

The other way around (Where "info" is the input text and "s" the binary version of it)

byte[] bytes = info.getBytes();
BigInteger bi = new BigInteger(bytes);
String s = bi.toString(2); 
杀手六號 2024-10-10 14:30:18

查看 parseInt 函数。您可能还需要强制转换和 Character.toString 函数。

Look at the parseInt function. You may also need a cast and the Character.toString function.

蓝色星空 2024-10-10 14:30:18

您也可以使用没有流和正则表达式的替代解决方案(基于卡萨布兰卡的答案):

public static String binaryToText(String binaryString) {
    StringBuilder stringBuilder = new StringBuilder();
    int charCode;
    for (int i = 0; i < binaryString.length(); i += 8) {
        charCode = Integer.parseInt(binaryString.substring(i, i + 8), 2);
        String returnChar = Character.toString((char) charCode);
        stringBuilder.append(returnChar);
    }
    return stringBuilder.toString();
}

您只需要附加指定的字符作为字符串到字符序列。

Also you can use alternative solution without streams and regular expressions (based on casablanca's answer):

public static String binaryToText(String binaryString) {
    StringBuilder stringBuilder = new StringBuilder();
    int charCode;
    for (int i = 0; i < binaryString.length(); i += 8) {
        charCode = Integer.parseInt(binaryString.substring(i, i + 8), 2);
        String returnChar = Character.toString((char) charCode);
        stringBuilder.append(returnChar);
    }
    return stringBuilder.toString();
}

you just need to append the specified character as a string to character sequence.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文