Java 进制转换并以字符串输出显示

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

1.bytes to hexa

	/**
	 * bytes to hex
	 * @param bytes
	 * @return
	 */
	public static String bytesToHexString(byte[] bytes) {
		if(bytes==null || bytes.length<1) {
			return null;
		}
		StringBuffer sb =new StringBuffer(bytes.length*2);;
		for (byte b : bytes) {
			sb.append(String.format("%02x", new Integer(b & 0xFF)));
		}
		return sb.toString();
	}
	

2.hexa to bytes

	/**
	 * hex to bytes 
	 * @return
	 */
	public static Byte[] hexToBytes(String hex) {
		if(hex==null || hex.length()<1) {
			return null;
		}
		int len=hex.length()/2;
		Byte[] bytes=new Byte[len];
		for (int i = 0; i < bytes.length; i++) {
			String str=hex.substring(i*2, i*2+2);
			bytes[i]=(byte) Integer.parseInt(str);
		}
		return bytes;
	}

3.测试

	public static void main(String[] args) {
		String decodeStr="AAABAlkAABgHMRY0NgAAAAAAAAA=";
		byte[] b= {50};
		System.out.println("Base64 decode to hexa:"+bytesToHexString(Base64.decode(decodeStr)));
		System.out.println("int 50 to hexa:"+bytesToHexString(b));
	}

4.结果

Base64 decode to hexa:0000010259000018073116343600000000000000
整数50的十六进制:32

猜你喜欢

转载自blog.csdn.net/qq_23315711/article/details/81356431