Java 中byte 與 char 的相互轉換

轉:http://blog.sina.com.cn/s/blog_6047c8870100qftt.htmlhtml

  • char轉化爲byte:

    public static byte[] charToByte(char c) {
        byte[] b = new byte[2];
        b[0] = (byte) ((c & 0xFF00) >> 8);
        b[1] = (byte) (c & 0xFF);
        return b;
    }htm

 

char[]轉化爲byte[]:blog

char[] cChar=new char[5]{a,b,c,d,e};  
byte[] byteData=Encoding.Default.GetBytes(cChar);  coding

// 這樣轉換,一個2字節的char,只轉換爲1個byte。static

 

byte[]轉化爲char[]:di

byte[] byteData=new byte[5]{0x01,0x02,0x03,0x04,0x05};  
char[] cChar=Encoding.ASCII.GetChars(byteData);  co

 

  • byte轉換爲char:

    public static char byteToChar(byte[] b) {
        char c = (char) (((b[0] & 0xFF) << 8) | (b[1] & 0xFF));
        return c;
    }new

相關文章
相關標籤/搜索