如何在Java中将字符串转换为二进制utf-16和将二进制转换为字符串?

0 java utf-16 string-decoding

我的项目需要将阿拉伯文本转换为二进制,然后将二进制转换为文本(反向过程)。我使用了这段代码,但是我注意到当我使用utf-16将字符串转换为二进制时,然后读取该二进制文件以将其转换回原始的UTF-16字符串会给我不同的字符

例如:编码中使用的阿拉伯字符为(?),由utf-16lE转换为二进制(0100011000000110)

现在,当我要将这些二进制位(0100011000000110)转换为原始utf-16字符串时,将给我不同的字符是F。

如果字符串是阿拉伯字符和utf-16编码,只会出现这些问题。我该如何解决这个问题呢?

// Convert the text to binary
public static String getBinaryFromText(String secretText) {
    byte[] bytes = secretText.getBytes(StandardCharsets.UTF_16LE);
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes) {
        int val = b;
        for (int i = 0; i < 8; i++) {
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
        }
    }

    return binary.toString();
}

// Convert the binary to text.
public static String getTextFromBinary(String binaryString) {
    String binary = binaryString.replace(" ", "");
    String binaryPer8Bits;
    byte[] byteData;
    byteData = new byte[binary.length() / 8];

    for (int i = 0; i < binary.length() / 8; i++) {
        // To divide the string into 8 characters
        binaryPer8Bits = binary.substring(i * 8, (i + 1) * 8);
        // The integer of decimal string of binary numbers
        Integer integer = Integer.parseInt(binaryPer8Bits, 2);
        // The casting to a byte type variable
        byteData[i] = integer.byteValue();
    }

    return new String(byteData);
}
Run Code Online (Sandbox Code Playgroud)

k5_*_*k5_ 5

使用new String(byteData);您解释byte[]使用默认编码的创建。要将其解释为UTF_16LE,您需要使用其他构造函数:

new String(byteData, StandardCharsets.UTF_16LE);

(几乎)从不使用new String(byte[])它将使用默认编码,因此您的应用程序将是平台依赖的。