开发者

Java Problem: creating a string from a sequence of bytes

I came across the following program and its showing unexpected results.

public class StringFromByte
{
       public static void main(String[] args)
       {
             byte bytes[] = new byte[256];

             for(int i = 0; i < 256; i++)
    开发者_运维百科             bytes[i] = (byte)i;

             String str = new String(bytes);
             for(int i = 0, n = str.length(); i < n; i++)
                 System.out.print((int)str.charAt(i) + " ");
       }
}  

Technically this program should print the integers from 0 to 255 in order. But if you ran the program sometimes it shows this sequence (0 to 255) sometimes it shows some other sequence. Its behavior is unspecified. What's going on?


The String constructor you're using uses a default character encoding. It could interpret some bytes as multi-byte characters.

Try this:

         String str = new String(bytes, CharSet.forName( "ISO-8859-1" ));

See also the CharSet API documentation, which lists standard CharSet names.

Disclaimer: I usually use this constructor for UTF-8.


Its behaviour is not unspecified.

A character is not the same thing as a byte, but the person who wrote this doesn't know that. There are about six million characters in unicode, but there are only 256 unique bytes. This means that many of the unicode characters are represented by more than one byte.

Some of the bytes in your example indicate that the character needs more than one byte, but I'm guessing that the "next" bytes in the array don't correspond to valid UTF-8 characters.

To properly encode a String from a set of bytes that are not UTF-8, use this constructor. You will have to provide the correct character set so Java can then understand how the bytes fit into characters.

The reason you're getting different results is because of the environment. Each environment has a default Locale which specifies it's preferred character set. The constructor you are using always assumes a UTF-8 character set, so some of the times it mistranslates the source bytes into gibberish.


Well, for starters, the maximum value a Java byte type can hold is 127 (the byte data type is an 8-bit signed two's complement integer).


Replace byte with char and it works as expected. It's because of byte's maximum 127.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜