字符串和字节数组的转换的字符集

1、将字符转换成byte数组

 String  str = "罗长";
 byte[] sb = str.getBytes();

2、将byte数组转换成字符

 byte[] b={(byte)0xB8,(byte)0xDF,(byte)0xCB,(byte)0xD9}; 
 String str= new String (b);

一、字符串转字节数组

String str = “金灿灿”;

byte[] bytes = str.getBytes();

如果转换的时候不设置编码格式,默认是以环境的字符集编码。

1.utf-8 : byte[] bytes = str.getBytes(“utf-8”);//中文是占三个字节

2.gbk : byte[] bytes = str.getBytes(“gbk”);//中文是占两个字节

二、字节数组转字符串

1.utf-8 : String s = new String(bytes ,“utf-8”);

2.gbk : String s = new String(bytes ,“gbk”);

扫描二维码关注公众号,回复: 9619140 查看本文章
发布了13 篇原创文章 · 获赞 0 · 访问量 310

猜你喜欢

转载自blog.csdn.net/q314050231/article/details/103283939