JAVA字符编码操作

public class HelloWorld{
	public static void main(String[] ages) throws Exception{
		String s="呵呵Hh";
		//转换成字节序列用的是项目默认的编码GBK
		byte[]bytes=s.getBytes();
		for (byte b:bytes) {
			//把字节(转换成了int)以16进制的方式显示
			System.out.print(Integer.toHexString(b&0xff)+" ");
		}
		
		System.out.println();
		byte[]bytes2=s.getBytes("gbk");
		//gbk编码中文占用2个字节,英文占用1个字节
		for (byte b:bytes2) {
			//把字节(转换成了int)以16进制的方式显示
			System.out.print(Integer.toHexString(b&0xff)+" ");
		}
		
		System.out.println();
		byte[]bytes3=s.getBytes("utf-8");
		//utf-8编码中文占用3个字节,英文占用1个字节
		for (byte b:bytes3) {
			//把字节(转换成了int)以16进制的方式显示
			System.out.print(Integer.toHexString(b&0xff)+" ");
		}
		
		System.out.println();
		//Java是双字节编码utf-16be
		byte[]bytes4=s.getBytes("utf-16be");
		//utf-16be编码中文占用2个字节,英文占用2个字节
		for (byte b:bytes4) {
			//把字节(转换成了int)以16进制的方式显示
			System.out.print(Integer.toHexString(b&0xff)+" ");
		}
		
		System.out.println();
		/*
		 * 当你的字节序列是某种编码时,这个时候想把字节序列变成字符串时,
		 * 也需要用这种编码方式,否则会出现乱码
		 */
		String str1=new String(bytes4);//用项目默认的编码
		System.out.println(str1);
		String str2	=new String(bytes4,"utf-16be");
		System.out.println(str2);
		
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值