Ejemplos

Este pequeño programa le permitirá analizar cómo se transforma una String en bytes según una cierta codificación:

// private static final String LETRAS = "aeiou áéíóú";

private static final String LETRAS =

    "aeiou u00E1u00E9u00EDu00F3u00FA";

 

public static void main(String[] args)

            throws UnsupportedEncodingException {

    encode("ISO-8859-1");   // ISO Latin-1

    encode("Cp1252");       // Windows Latin-1

    encode("MacRoman");     // Macintosh Roman

    encode("UTF-8");

    encode("UTF-16BE");

    encode("UTF-16LE");

}

 

private static void encode(String name)

        throws UnsupportedEncodingException {

    byte[] bytes = LETRAS.getBytes(name);

    System.out.printf("%-12s:%d:", name, bytes.length);

    for (byte b : bytes)

        System.out.printf(" %02x", b);

    System.out.println();

}

Resultado de ejecución:

carácter:       a  e  i  o  u     á  é  í  ó  ú

ISO-8859-1:11: 61 65 69 6f 75 20 e1 e9 ed f3 fa

Cp1252    :11: 61 65 69 6f 75 20 e1 e9 ed f3 fa

MacRoman  :11: 61 65 69 6f 75 20 87 8e 92 97 9c

UTF-8     :16: 61 65 69 6f 75 20 c3 a1 c3 a9 c3 ad c3 b3 c3 ba

UTF-16BE  :22:

  00 61 00 65 00 69 00 6f 00 75 00 20 00 e1 00 e9 00 ed 00 f3 00 fa

UTF-16LE  :22:

  61 00 65 00 69 00 6f 00 75 00 20 00 e1 00 e9 00 ed 00 f3 00 fa 00

Temas relacionados

32. Codificación de caracteres [encoding]