您的位置 首页 java

java中的char占几个字节

1:“字节”是byte,“位”是bit ;

2: 1 byte = 8 bit ;

char java 中是2个字节。java采用unicode,2个字节(16位)来表示一个字符。

例子代码如下:

[java] view plain copy

print?

  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= “中”;
  4. char x =’中’;
  5. byte[] bytes =null;
  6. byte[] bytes1=null;
  7. try {
  8. bytes = str.getBytes(“utf-8”);
  9. bytes1 = charToByte(x);
  10. } catch (Unsupported encoding Exception e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. System.out.println(“bytes 大小:”+bytes. length );
  15. System.out.println(“bytes1大小:”+bytes1.length);
  16. }
  17. public static byte[] charToByte(char c) {
  18. byte[] b = new byte[2];
  19. b[0] = ( byte) ((c & 0xFF00) >> 8);
  20. b[1] = ( byte) (c & 0xFF);
  21. return b;
  22. }
  23. }

运行结果:

bytes 大小:3

bytes1大小:2

java是用unicode来表示字符,”中”这个中文字符的unicode就是2个字节。

String.getBytes(encoding)方法是获取指定 编码 的byte数组表示,

通常 gbk /gb2312是2个字节,utf-8是3个字节

如果不指定encoding则取系统默认的encoding。

文章来源:智云一二三科技

文章标题:java中的char占几个字节

文章地址:https://www.zhihuclub.com/180742.shtml

关于作者: 智云科技

热门文章

网站地图