JAVA 比较方便的十六进制转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33335577/article/details/82150347

import java.util.Arrays;

public class ToHex {

	public static void main(String[] args) {
		//字节数组
		byte[] bs = new byte[]{105,111,46,105,111,117,116,105,108,13,10,83,85,67,67,69,83,83,13,10,103,111,108,97,110,103,13,10,49,50,51,52,53,53,13,10,114,111,111,116,13,10,115,100,97,49,50,51,52};
		System.out.println("原始数据:"+Arrays.toString(bs));
		StringBuffer stringBuffer = new StringBuffer();
		//字节数组转十六进制
		for (int i = 0; i < bs.length; i++) {
			//%X 十六进制大写,%x 十六进制小写
			String format = String.format("%02X", bs[i]);
			//if (format.length() == 1) {
			//	stringBuffer.append("0");
			//}
			stringBuffer.append(format);
		}
		System.out.println("转十六进制:"+stringBuffer.toString());
		byte[] bs1 = new byte[stringBuffer.length() / 2];
		for (int i = 0; i < bs1.length; i++) {
			//截取
			String str = stringBuffer.subSequence(i*2,(i+1)*2).toString();
			//转换为byte
			bs1[i] = Byte.parseByte(str,16);
		}
		System.out.println("十六进制转字节数组:"+Arrays.toString(bs1));
		System.out.println("结果对比:"+Arrays.toString(bs).equals(Arrays.toString(bs1)));
	}

}

猜你喜欢

转载自blog.csdn.net/qq_33335577/article/details/82150347