Java 中byte 與 char 的相互轉換 Java基礎 但是很重要


  • 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;
    }

 

char[]轉化為byte[]:

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

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

 

byte[]轉化為char[]:

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

 

  • byte轉換為char:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM