String s = "一"; byte[] by = s.getBytes(); System.out.println(Integer.toString(a&0xff, 2)); //结果输出为11100100//-28 10111000//-72 10000000//-128 unicode 0100 ,1110 00,00 0000 根据utf-8的编码规则,输出正是“1”的unicode值。 String.getBytes的API描述:Encodes this String into a sequence of bytes using the platform's default charset。 其是与平台默认编码相关的。 在我的机器上, System.out.println(Charset.defaultCharset().name()); 输出为UTF-8,默认编码。
byte[] by = s.getBytes();
System.out.println(Integer.toString(a&0xff, 2));
//结果输出为11100100//-28
10111000//-72
10000000//-128
unicode 0100 ,1110 00,00 0000 根据utf-8的编码规则,输出正是“1”的unicode值。
String.getBytes的API描述:Encodes this String into a sequence of bytes using the platform's default charset。
其是与平台默认编码相关的。
在我的机器上,
System.out.println(Charset.defaultCharset().name());
输出为UTF-8,默认编码。
如表:
1字节 0xxxxxxx
2字节 110xxxxx 10xxxxxx
3字节 1110xxxx 10xxxxxx 10xxxxxx
4字节 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5字节 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
6字节 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
因此UTF-8中可以用来表示字符编码的实际位数最多有31位,即上表中x所表示的位。除去那些控制位(每字节开头的10等),这些x表示的位与UNICODE编码是一一对应的,位高低顺序也相同。
实际将UNICODE转换为UTF-8编码时应先去除高位0,然后根据所剩编码的位数决定所需最小的UTF-8编码位数。
因此那些基本ASCII字符集中的字符(UNICODE兼容ASCII)只需要一个字节的UTF-8编码(7个二进制位)便可以表示。