Java's char type is 16-bit unicode

  • Java is a 16-bit unicode char type, but also Chinese, two bytes, but if (general system default) or with utf-8 is converted to an array of bytes read, will become 3 bytes.
  • Unicode character set, UTF-8 / UTF-16 encoding rules, or generalized Unicode character set and including a plurality of encoding rules. That character set specified binary code, each character encoding rules only specifies how to store the binary code.
  • Then utf-16 you a question about the big-endian (Big Endian order) and the little-endian (Little Endian order) are (more complex utf-8, so it is best not to cause programming under windows).
  • In Java, a Chinese character for char, getByte result, if not specified coding rule, the default is UTF-8, a Chinese 3 bytes , if unicode or utf-16, default is 4 bytes, the first two bytes represented 0xFEFF big endian, 0xFFEF indicates little-endian , if specified utf-16be or utf-16le, is 2 bytes ,
package IOTest;

import javax.management.StandardEmitterMBean;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class CharTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //Java的char是两字节的Unicode字符(0-65535)
        char b='中';
        System.out.println((int)b);
        byte[] bs=char2Byte(b);
        System.out.println(byte2HexString(bs));
        byte[] cs=String.valueOf(b).getBytes("unicode");
        byte[] ds=String.valueOf(b).getBytes(StandardCharsets.UTF_16BE);
        byte[] es=String.valueOf(b).getBytes(StandardCharsets.UTF_16LE);
        byte[] fs=String.valueOf(b).getBytes(StandardCharsets.UTF_16);
        byte[] gs=String.valueOf(b).getBytes(StandardCharsets.UTF_8);
        System.out.println(byte2HexString(cs));
        System.out.println(byte2HexString(ds));
        System.out.println(byte2HexString(es));
        System.out.println(byte2HexString(fs));
        System.out.println(byte2HexString(gs));
    }
    public static byte[] char2Byte(char c){
        byte[] ans=new byte[2];
        ans[1]=(byte)(c&0x00ff);
        ans[0]=(byte)((c&0xff00)>>8);
        return ans;
    }
    public static String byte2HexString(byte[] bs){
        StringBuilder sb=new StringBuilder();
        for(byte b:bs){
            int c=b&0x0f;
            if(c<10){
                sb.append(c);
            }else{
                sb.append((char)((c-10)+'A'));
            }
            c=(b&0xf0)>>4;
            if(c<10){
                sb.append(c);
            }else{
                sb.append((char)((c-10)+'A'));
            }
            sb.append(' ');
        }
        return sb.toString();
    }
}

Guess you like

Origin www.cnblogs.com/zxcoder/p/12571295.html