码迷,mamicode.com
首页 > 编程语言 > 详细

Java 中byte 与 char 的相互转换 Java基础 但是很重要

时间:2017-10-04 23:52:30      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:byte   new   return   static   一个   default   转化   基础   ret   

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

Java 中byte 与 char 的相互转换 Java基础 但是很重要

标签:byte   new   return   static   一个   default   转化   基础   ret   

原文地址:http://www.cnblogs.com/zhanghengscnc/p/7627464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!