如何将字符串转换为 UTF-16?

How to convert a string to UTF-16?

我正在将下面的目标代码转换为 java,但是 java 代码没有给我与此代码相同的结果

NSData *inputData = [pm dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
NSString *encodedString = [inputData base64EncodedString];
pm = [IFunctions replaceString:encodedString replaceChar:@"=" replaceWithChar:@"-"];

Java代码:

String s_decoded = new String(pm.getBytes(), "UTF-16LE");
pm = Base64.encode(s_decoded.getBytes()).toString().replace("=", "-");

无参数 getBytes() 方法使用平台默认编码,可能不是 UTF-16LE。试试 getBytes("UTF-16LE").

参考此代码并修改您的代码。

public class UseTheForce {
        public static void main(final String[] args)
            throws java.io.UnsupportedEncodingException {
            for (final byte b : args[0].getBytes(args[1])) {
                System.out.printf("%1X ", (b & 0xFF));
            }
            System.out.println();
        }
    }
    Test

    $ java UseTheForce luke US-ASCII
    6C 75 6B 65

    $ java UseTheForce luke UTF-8
    6C 75 6B 65

    $ java UseTheForce luke UTF-16
    FE FF 00 6C 00 75 00 6B 00 65

    $ java UseTheForce luke UTF-16BE
    00 6C 00 75 00 6B 00 65

    $ java UseTheForce luke UTF-16LE
    6C 00 75 00 6B 00 65 00

    $ java UseTheForce luke UTF-32
    00 00 00 6C 00 00 00 75 00 00 00 6B 00 00 00 65
byte[]   bytesEncoded = Base64.encodeBase64(str.getBytes("UTF-16LE"));
String stringEncoded = new String(bytesEncoded);

您需要使用 getBytes() 方法并指定所需的字符集:

public static void main(String[] args) throws UnsupportedEncodingException {
    char ch;
    ch = 0x0001;
    System.out.println(Arrays.toString((String.valueOf(ch)).getBytes(StandardCharsets.UTF_16LE)));
    ch = 0x0111;
    System.out.println(Arrays.toString((String.valueOf(ch)).getBytes(StandardCharsets.UTF_16LE)));
    ch = 0x1111;
    System.out.println(Arrays.toString((String.valueOf(ch)).getBytes(StandardCharsets.UTF_16LE)));
}

输出:

[1, 0]
[17, 1]
[17, 17]

我用了getBytes(StandardCharsets.UTF_16LE)