Showing posts with label Encoding. Show all posts
Showing posts with label Encoding. Show all posts

Sunday, May 10, 2015

Endianness and Byte Order Mark (BOM)

What is Endianness and Byte Order Mark (BOM)?

The encoding scheme such as UTF-16 and UTF-32 has to handle the endianness of their code units. This is because each single code unit of them having the size bigger than 8-bits, the size where computer organizing its memory unit. This makes the bytes order important to interpret the correct data. There are 2 type of endianness, Big-Endian, and Little-Endian. In Big-Endian order, data is read/wrote from the most significant byte first and subsequently until the least significant byte. This is basically same as the human nature in reading/writing a number. On the other hand, Little-Endian doing the opposite way by reading/writing the least significant byte first and subsequently until the most significant byte. An easy way to memorize them is: Big-Endian is big number start first; Little-Endian is little number start first.

UTF-16 and UTF-32 rely on Byte Order Mark (BOM), which is the special Unicode character to indicate the endianness of the byte stream. BOM has code point U+FEFF, which is a 2 bytes number. FE is the most significant byte, and FF is the least significant byte. By only looking to the individual bytes, you may confused that FF should be the most significant byte as it is bigger than FE, this is wrong! In fact, FE is most significant byte because it is FE00, add with FF to become FEFF. BOM has to be attached in the starting of the byte stream. So that it could be examined first and determine the order of the following byte stream. The program below showing the code units of encoded BOM by different encoding schemes.

public static void main(String[] args) {
    printBom(Charset.forName("UTF-8"));
    printBom(Charset.forName("UTF-16"));
    printBom(Charset.forName("UTF-16LE"));
    printBom(Charset.forName("UTF-16BE"));
    printBom(Charset.forName("UTF-32"));
    printBom(Charset.forName("UTF-32LE"));
    printBom(Charset.forName("UTF-32BE"));
}

private static void printBom(Charset charset) {
    String bom = "\uFEFF";
    System.out.format("%s >> ", charset.displayName());
    for (byte b : bom.getBytes(charset)) {
        System.out.format("%02x ", b);
    }
    System.out.println("");
}

Result:

EncodingCode Units
UTF-8ef bb bf
UTF-16feff feff
UTF-16LEfffe
UTF-16BEfeff
UTF-320000feff
UTF-32LEfffe0000
UTF-32BE0000feff

How to use UTF-16?

When encoding, UTF-16 always write Big-Endian BOM in the beginning and follow by byte stream in Big-Endian order.

public static void main(String[] args) {
    String bom = "a";
    for (byte b : bom.getBytes(Charset.forName("UTF-16"))) {
        System.out.format("%02x ", b);
    }
    System.out.println("");
    //Result(in hexdecimal): fe ff 00 61
    //Result(in decimal): -2 -1 00 97
}

When decoding, UTF-16 will examine the BOM in order to determine the endianness of the following byte stream. If no BOM provided, then it will assume the byte stream in Big-Endian order.

public static void main(String[] args) {
    Charset utf16 = Charset.forName("UTF-16");
    byte[] beBytes = new byte[]{-2, -1, 00, 97};
    String beResult = new String(beBytes, utf16);

    byte[] leBytes = new byte[]{-1, -2, 97, 00};
    String leResult = new String(leBytes, utf16);

    byte[] noBomBeBytes = new byte[]{00, 97};
    String noBomBeResult = new String(noBomBeBytes, utf16);

    byte[] noBomLeBytes = new byte[]{97, 00};
    String noBomLeResult = new String(noBomLeBytes, utf16);

    System.out.format("Big Endian Decoded Result(beResult): %s%n"
            + "Little Endian Decoded Result(leResult): %s%n"
            + "No BOM Big Endian Decoded Result(noBomBeResult): %s%n"
            + "No BOM Little Endian Decoded Result(noBomLeResult): %s%n"
            + "beResult equals leResult: %b%n"
            + "beResult equals noBomBeResult: %b%n"
            + "beResult equals noBomLeResult: %b%n",
            beResult, leResult, noBomBeResult, noBomLeResult,
            beResult.equals(leResult), beResult.equals(noBomBeResult),
            beResult.equals(noBomLeResult));
}

Result:
Big Endian Decoded Result(beResult): a
Little Endian Decoded Result(leResult): a
No BOM Big Endian Decoded Result(noBomBeResult): a
No BOM Little Endian Decoded Result(noBomLeResult): 愀
beResult equals leResult: true
beResult equals noBomBeResult: true
beResult equals noBomLeResult: false

Potential pitfall of using UTF-16 with multiple texts

Be careful when using UTF-16 to encodes multiple texts into a single byte stream. This is because it will always add BOM for every single text. The program below demonstrates the problem.

public static void main(String[] args) throws IOException {
    Charset utf16 = Charset.forName("UTF-16");
    String ping = "ping";
    String pong = "pong";
    String pingpong = ping + pong;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(ping.getBytes(utf16));
    baos.write(pong.getBytes(utf16));

    byte[] encodedBytes = baos.toByteArray();
    printBytes(encodedBytes);
    String decodedResult = new String(encodedBytes, utf16);

    System.out.format("DecodeResult: %s%nDecodeResult equals original: %b%n",
            decodedResult, decodedResult.equals(pingpong));
}

private static void printBytes(byte[] bytes) {
    for (byte b : bytes) {
        System.out.format("%02x ", b);
    }
    System.out.println("");
}

Result:
fe ff 00 70 00 69 00 6e 00 67 fe ff 00 70 00 6f 00 6e 00 67
DecodeResult: pingpong
DecodeResult equals original: false

Solution

Direct dealing with encoded/decoded bytes is always a bad idea. While we still can handle the BOM issue introduced by UTF-16 above by ourselves, why not just leave the hard work to existing Java API. Use the java.io.OutputStreamWriter instead, and the issue will be resolved.

public static void main(String[] args) throws IOException {
    Charset utf16 = Charset.forName("UTF-16");
    String ping = "ping";
    String pong = "pong";
    String pingpong = ping + pong;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(baos, utf16);
    osw.write(ping);
    osw.write(pong);
    osw.flush();

    byte[] encodedBytes = baos.toByteArray();
    printBytes(encodedBytes);
    String decodedResult = new String(encodedBytes, utf16);

    System.out.format("DecodeResult: %s%nDecodeResult equals original: %b%n",
            decodedResult, decodedResult.equals(pingpong));
}

Result:
fe ff 00 70 00 69 00 6e 00 67 00 70 00 6f 00 6e 00 67
DecodeResult: pingpong
DecodeResult equals original: true

How UTF-16 encodes bytes in Little-Endian order?

After all, you may wonder how UTF-16 to encode bytes in Little-Endian order. It can't, because it is by default write Big-Endian BOM only. Hence. to generate Little-Endian byte stream with Little-Endian BOM, we have to make use of x-UTF-16LE-BOM.

public static void main(String[] args) {
    String bom = "a";
    for (byte b : bom.getBytes(Charset.forName("x-UTF-16LE-BOM"))) {
        System.out.format("%02x ", b);
    }
    System.out.println("");
    //Result(in hexdecimal): ff fe 61 00
    //Result(in decimal):  -1 -2 97 00 
}

UTF-16 in other forms

BOM is not the only approach to deal with endianness. There are UTF-16BE and UTF-16LE encoding scheme which describe endianness natural of their byte stream by their name. Due to this, they do not require BOM in their byte stream. When encoding, they never write BOM. When decoding, if BOM exist, they will take it as a ZERO-WIDTH NON-BREAKING SPACE.

Using UTF-16 is a bit tricky. Hence, make sure you are using the correct encoding scheme for encoding and decoding.

Encoded ByDecoded ByResultReason
UTF-16UTF-16BEOKEncoded bytes of UTF-16 is Big-Endian, the initial BOM will be
 treated as ZERO-WIDTH NON-BREAKING SPACE
UTF-16UTF-16LENOEncoded bytes of UTF-16 is Big-Endian, cannot be decoded
correctly by Little-Endian encoding.
UTF-16BEUTF-16OKWhen there is no initial BOM, UTF-16 will assume the byte stream
 is Big-Endian
UTF-16BEUTF-16LENOThe endian of encoding scheme used for encoding and decoding
is totally contrast.
UTF-16LEUTF-16NOUTF-16 is only able to decode Big-Endian byte stream if there is
no initial BOM.
x-UTF-16LE-BOMUTF-16OKUTF-16 could interpret the initial BOM
The same thing is this section applied to UTF-32, UTF-32BE, and UTF-32LE.

BOM in UTF-8

BOM is not necessary for UTF-8 because it does not have the endianness issue. Each of UTF-8 code unit is 8-bits, which is same as the computer memory unit. However, it is not prohibited to put the initial BOM to UTF-8 encoded byte stream. The initial BOM will be treated as ZERO-WIDTH NON-BREAKING SPACE. You could read this Wikipedia page to get some idea why people still using BOM for UTF-8.

Related topics:
Character Encoding Terminologies
Unicode Support in Java
Encoding and Decoding
Surrogate Characters Mechanism
Unicode Regular Expression
Characters Normalization
Text Collation

References:
http://en.wikipedia.org/wiki/Endianness
http://en.wikipedia.org/wiki/Byte_order_mark
http://en.wikipedia.org/wiki/UTF-16
http://en.wikipedia.org/wiki/UTF-8
http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html

Encoding and Decoding

How to perform encoding and decoding in Java?

Using Charset class

We use java.nio.charset.Charset to instantiate the encoding scheme that we want to use. It provides the following methods for encoding and decoding.

  • Encoding
    • ByteBuffer encode(CharBuffer cb)
    • ByteBuffer encode(String str)
  • Decoding
    • CharBuffer decode(ByteBuffer bb)

Using String class

While Charset is coming from the perspective of encoding scheme, if we would like to start from the perspective of texts/characters, then java.lang.String is the class to go as it is used to handle texts/characters in most of the time. It provides the following API for encoding characters and decoding byte arrays.
  • Encoding
    • byte[] getBytes()
    • byte[] getBytes(Charset charset)
    • byte[] getBytes(String charsetName)
  • Decoding
    • String (byte[] bytes)
    • String (byte[] bytes, Charset charset)
    • String (byte[] bytes, int offset, int length)
    • String (byte[] bytes, int offset, int length, Charset charset)
    • String (byte[] bytes, int offset, int length, String charsetName)
    • String (byte[] bytes, String charsetName)

Using CharsetEncoder and CharsetDecoder class

Furthermore, if you want more control over encoding/decoding, then you can use java.nio.CharsetEncoder and java.nio.CharsetDecoder instance which is created by java.nio.charset.Charset. For example,

String copyRight = "\u00A9";
Charset charset = Charset.forName("US-ASCII");
byte[] bytes = copyRight.getBytes(charset);
System.out.println(new String(bytes, charset)); // print default replacement "?"

The code sample above using String to encode and decode a character. However, that character encoding scheme (ASCII) is not able to encode/decode the character, and hence it falls back to default replacement character, which is "?" mark. Using CharcetEncoder and CharsetDecoder, we could set the replacement character as we want.

String copyRight = "\u00A9";
Charset charset = Charset.forName("US-ASCII");
CharsetEncoder encoder = charset.newEncoder();
// When character is unmapped, trigger replace action
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
encoder.replaceWith("!".getBytes(charset)); // set Exclamation mark as replacement
ByteBuffer byteBuffer = encoder.encode(CharBuffer.wrap(copyRight.toCharArray()));
byte[] bytes = new byte[byteBuffer.limit()];
byteBuffer.get(bytes);
System.out.println(new String(bytes, charset)); // print new replacement "!"

What is the bytes outcome of encoded character?

Different encoding schemes give different of encoded results for a particular character/code point. Same applied to those encoding schemes that based on the same standard such as UTF-8 and UTF-16 which based on Unicode standard.

public static void main(String[] args) {
    printEncodedBytesForOmega(Charset.forName("UTF-8"));
    printEncodedBytesForOmega(Charset.forName("UTF-16BE"));
    printEncodedBytesForOmega(Charset.forName("IBM935"));
    printEncodedBytesForOmega(Charset.forName("Cp949"));
    printEncodedBytesForOmega(Charset.forName("MS932"));
}

private static void printEncodedBytesForOmega(Charset charset) {
    byte[] bytes = "Ω".getBytes(charset);
    System.out.format("%s >> ", charset.displayName());
    for (byte b : bytes) {
        System.out.format("%02x ", b);
    }
    System.out.println("");
}

The code sample above giving the result as below:

Encoding SchemeEncoded Bytes (Hex)
UTF-8 ce a9 
UTF-16BE03 a9
x-IBM9350e 41 78 0f 
x-IBM949a5 d8 
windows-31j83 b6
Therefore, it is important to use the same encoding scheme to decode the byte stream which was encoded by that particular encoding scheme. If not, you may get unexpected characters or even something that look like corrupted.

public static void main(String[] args) {
    String omega = "Ω";
    byte[] encodedBytes = omega.getBytes(Charset.forName("UTF-8"));
    String decodedString = new String(encodedBytes, Charset.forName("UTF-16BE"));
    System.out.format("Decoded string equals to original string: %b,%n"
            + "Decoded string: %s%n", decodedString.equals(omega), decodedString);
    // Decoded string equals to original string: false,
    // Decoded string: 캩
}

The size of the encoded bytes sequence/number of code unit is not fixed. For example, UTF-8 could take 1 to 4 code units (each code unit 1 byte) for a code point, while UTF-16 could take 1 to 2 code units(each code unit 2 bytes) for a code point.

Characters Unicode NameCode pointUTF-8 Code UnitsUTF-16BE Code UnitsUTF-32BE Code Units
aLatin Small Letter AU+006161006100000061
©Copyright signU+00A9C2 A900A9000000A9
₂Subscript twoU+2082E2 82 82208200002082
𝅘𝅥𝅮Musical Symbol Eighth NoteU+1D160F0 9D 85 A0D834 DD600001D160 

Potential pitfall of fixing the bytes container size

Due to the fact above, never assume that 1 byte is equivalent to 1 code point. Fix the number for byte array size for each code point is not working as well. The program below showing this problem.

public static void main(String[] args) throws IOException {
    Charset charset = Charset.forName("UTF-8");
    String original = "a©₂\uD834\uDD60";
    byte[] encoded = original.getBytes(charset);
    InputStream stream = new ByteArrayInputStream(encoded);
    String decoded = decodeFromStream(stream, charset);

    System.out.format("Original: %s%nDecoded:%s%nOriginal==Decoded:%b%n",
            original, decoded, original.equals(decoded));
}

private static String decodeFromStream(InputStream stream, Charset encoding)
throws IOException {
    StringBuilder builder = new StringBuilder();
    byte[] buffer = new byte[1]; // Change the byte array size doesn't help
    while (true) {
        int r = stream.read(buffer);
        if (r < 0) {
            break;
        }
        String data = new String(buffer, 0, r, encoding);
        builder.append(data);
    }
    return builder.toString();
}

Result:
Original: a©₂𝅘𝅥𝅮
Decoded:a?????????
Original==Decoded:false

Solution

Instead of direct dealing with encoded byte stream, use java.io.InputStreamReader to decodes the byte stream. It is able to decode byte stream and return code point accordingly.

private static String decodeFromStream(InputStream stream, Charset encoding)
throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader isr = new InputStreamReader(stream, encoding);
    while (true) {
        //What has been read is codepoint, instead of encoded code unit.
        int codepoint = isr.read(); 
        if (codepoint < 0) {
            break;
        }
        builder.append(Character.toChars(codepoint ));
    }
    return builder.toString();
}

Result:
Original: a©₂𝅘𝅥𝅮
Decoded:a©₂𝅘𝅥𝅮
Original==Decoded:true

Related topics:
Character Encoding Terminologies
Unicode Support in Java
Endianness and Byte Order Mark (BOM)
Surrogate Characters Mechanism
Unicode Regular Expression
Characters Normalization
Text Collation

References:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetEncoder.html
https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetDecoder.html
http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html

Character Encoding Terminologies

Character Encoding Terminologies

Down to the root, the computer could only recognize number in bit sequence. It relies on character encoding scheme to recognizes characters/symbols from human's world. Before we dive into programming with Unicode, it is important to know the character encoding terminologies in order to understand how it works when come to programming in Java.

General Character Encoding

General character encoding overview

Character is a generic term which representing a normal character in any languages, symbol, control character, formatting character, and etc. It is an abstract form which just a piece of textual data without any specific appearance or style. In any general character encoding, each of the characters is encoded into a unique integer value called as Code Point. Once the bonding between character and code point is established, this relationship is never changed and hence called as Encoded Character. Every character encoding scheme can only cope with certain Code Space, which is the range of integer value or total number of code points, depend on the bit-length that they are supporting.

Encoding Bit lengthCode space size
ASCII 7128
WINDOWS-12528256
On the other hand, the code space has determined the maximum number of distinct characters that the corresponding Character Set could contain. The term of Character set is a standard. It defines and contains only certain of characters. There are a lot of character sets out there. For example, Windows has various character sets specifically for different languages such as Arabic (Window 1256), Korean (Windows 949), Western European (Windows 1252) and etc.

CharSet basically is the short form of Coded Character Set, a set of characters which are encoded by specific character encoding scheme. Therefore, charset name most of the time same as character encoding name. Code Page is referring to the same thing, but this term is normally used by computer vendors. For example, UTF-8 has code page numbers 1208 at IBM, 65001 at Microsoft, 4110 at SAP.

What displayed on the screen is called Glyph Image. Font is a collection of glyphs with certain format and style setting. A font type does not necessary to cover all characters from a character set. For example, Arial font is not able to render Japanese characters because it does not contain any glyph for Japanese characters. What is probably rendered on the screen is just a square box. This means the textual data is there but no glyph to depict and render it on the screen. The Japanese characters will be rendered correctly when we use Arial Unicode MS instead.

Unicode Encoding

Unicode encoding


























Universal Character Set (UCS) is an International Standard(ISO/IEC 10646) that defines a standard set of characters that cover all characters from all around the World. It is developed in conjunction with Unicode standard, and hence it's size is determined by Unicode encoding code space. Initially, Unicode was only intended to covers all characters from all modern languages. The Unicode-based encoding scheme at that time was USC-2 (2-byte Universal Character Set), which is 16-bit and it has 65536 code space. However, since Unicode 2.0, UCS-2 was superseded by UTF-16 and Unicode code space is greatly extended to 1,114,112 by using surrogate characters mechanism. In other words, there are over 1 million code points or character placeholders available for characters in USC. USC currently contains nearly one hundred thousand abstract characters and there is still a lot of room for growth.

In term of the code point, Unicode taking the same approach, but it treats the code point as a layer between the character and the encoded value. Code point in Unicode has the notation U+following by hexadecimal numbers. Besides, Unicode also defines properties such as Name,Category, Script, Block, different Binary type and etc for each character. Each character is still mapped to a unique code point. Code point then is encoded by the Unicode-based character encoding scheme. The well-known encoding such as UTF-8, UTF-16, and UTF-32. Different Unicode encoding would encode the same code point into different bytes sequence(represented in hexadecimal format) with variable length of Code Unit. Example as below.

Characters Unicode NameCode pointUTF-8 Code UnitsUTF-16BE Code UnitsUTF-32BE Code Units
aLatin Small Letter AU+006161006100000061
©Copyright signU+00A9C2 A900A9000000a9
₂
Subscript twoU+2082E2 82 82208200002082
𝅘𝅥𝅮Musical Symbol Eighth NoteU+1D160F0 9D 85 A0D834 DD600001D160
A question to wrap up. UTF-16 could encode over 1 million code points, how about UTF-8? It probably could handle half of code space of UTF-16? The answer is No, UTF-8 also having the same code space as UTF-16. I hope you understand why.