6.4 编码解码测试

编码解码

编码(encode): 由字节到字符
解码(decode): 由字符到字节
在编码解码过程中使用了字符集。

编码解码测试

code

import java.io.UnsupportedEncodingException;

/**
 * 编码:字符串-->字节数组
 * 解码:字节数组-->字符串
 * @author dxt
 *
 */
public class TestEncode {
	public static void main(String[] args) throws UnsupportedEncodingException{
		String msg = "茅屋为秋风所破歌";
		//1. 编码: getBytes(): 对msg依据不同字符集进行编码, 字符串-->字节
		byte[] datas = msg.getBytes();
		//默认使用工程字符集进行编码,UTF-8中每个字占3个字节,所以length = 3 x 8 = 24
		System.out.println(datas.length);
		
		//编码:编码成其他字符集
		datas = msg.getBytes("GBK");	//GBK中每个汉字占2个字节,字母占1个字节
		System.out.println(datas.length);
		
		//2. 解码
		msg = new String(datas, 0, datas.length, "GBK");
		System.out.println(msg);
		
		//3. 乱码
		//3.1 字节数不够
		msg = new String(datas, 0, datas.length-2, "GBK");
		System.out.println(msg);
		msg = new String(datas, 0, datas.length-1, "GBK");
		System.out.println(msg);
		//3.2 字符集不同一
		msg = new String(datas);	//默认使用的字符集为工程字符集(UTF-8)
		System.out.println(msg);
		
	}
}

result
结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值