Java Строка getBytes () - PullRequest
       66

Java Строка getBytes ()

0 голосов
/ 29 апреля 2020

В java один символ равен двум байтам.

Но почему код ниже возвращает 2, а не 4?

public static void main(String[] args) {

        byte[] b = new String(new char[] {'H', 'I' }).getBytes();
        System.out.println(b.length);

}

1 Ответ

1 голос
/ 29 апреля 2020

getBytes() кодирует символы Unicode в Charset JVM по умолчанию, обычно ISO-8859-1 или UTF-8, оба из которых используют один байт для хранения этих символов.

Этот код должен помогите проиллюстрировать, что происходит:

public static void main(String[] args) throws Exception {
    test("ISO-8859-1", new char[] { 'H', 'I' });
    test("UTF-8"     , new char[] { 'H', 'I' });
    test("UTF-16LE"  , new char[] { 'H', 'I' });
    test("UTF-32LE"  , new char[] { 'H', 'I' });
    test("ISO-8859-1", new char[] { '⅓', '⅔' });
    test("UTF-8"     , new char[] { '⅓', '⅔' });
    test("UTF-16LE"  , new char[] { '⅓', '⅔' });
    test("UTF-32LE"  , new char[] { '⅓', '⅔' });
    test("UTF-8"     , "??");
    test("UTF-16LE"  , "??");
    test("UTF-32LE"  , "??");
}
static void test(String charsetName, char[] chars) throws Exception {
    test(charsetName, new String(chars));
}
static void test(String charsetName, String input) throws Exception {
    byte[] bytes = input.getBytes(charsetName);
    System.out.printf("%-12s %-6s", charsetName, new String(bytes, charsetName));
    for (byte b : bytes)
        System.out.printf(" %02x", b);
    System.out.println();
}

Вывод

ISO-8859-1   HI     48 49
UTF-8        HI     48 49
UTF-16LE     HI     48 00 49 00
UTF-32LE     HI     48 00 00 00 49 00 00 00
ISO-8859-1   ??     3f 3f
UTF-8        ⅓⅔     e2 85 93 e2 85 94
UTF-16LE     ⅓⅔     53 21 54 21
UTF-32LE     ⅓⅔     53 21 00 00 54 21 00 00
UTF-8        ??   f0 9f 98 80 f0 9f 91 8d
UTF-16LE     ??   3d d8 00 de 3d d8 4d dc
UTF-32LE     ??   00 f6 01 00 4d f4 01 00
...