Java 进制转换

package com.test;


public class A {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//其他进制转10进制
	    System.out.println("2转10 :"+ Integer.valueOf("1010",2).toString());
	    System.out.println("8转10 :"+ Integer.valueOf("125",8).toString() );
	    System.out.println("16转10:"+ Integer.valueOf("ABCDEF",16).toString()); 
		//10进制转其他进制
		int a = 11;
		System.out.println("10转2 :"+ Integer.toBinaryString(a));
		System.out.println("10转8 :"+ Integer.toOctalString(a));
		System.out.println("10转16:"+ Integer.toHexString(a));
		
		//16进制字符串
		String hex = "5a5a";
		System.out.println("16进制字符串转字节数组:");
		int len = hex.length();
	    byte[] hexbytes = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        //16进制  16位, 字节8位, 所以16进制1位 占  字节的4位, 两位组成8位字节
	    	hexbytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
	    }
	    
	    //字节数组转16进制
	    System.out.println("字节数组转16进制:");
	    hex = null;
	    for (int i = 0; i < hexbytes.length; i++) {
	    	hex = Integer.toString(hexbytes[i] & 0xff, 16);
	    	if(hex.length() == 1)
	    		hex = "0" + hex;
	    	System.out.print(hex+",");
		}
		
	    //字节
		byte b = hexbytes[0];
		char c = (char) (((hexbytes[0] & 0xFF) << 8) | (hexbytes[1] & 0xFF)); 
		System.out.println(c);
		
		byte[] intbytes = {0x00,0x00,0x00,0x31};
		//高位在前,低位在后  字节8位,int32位,所以4个字节为1个int
		int chunktype = (int)(intbytes[0] & 0xff)<<24 | (intbytes[1] & 0xff)<<16 | (intbytes[2] & 0xff)<<8 | (intbytes[3] & 0xff);
		System.out.println("字节数组转int:"+chunktype);
		
	}
	
	/**
	 * 自动补零
	 * @param code
	 * @param num
	 * @return
	 */
	private static String autoGenericCode(String code, int num) {
        // 保留num的位数
        // 0 代表前面补充0
        // d 代表参数为正数型 
		code = String.format("%0" + num + "d", Integer.parseInt(code));
        return code;
    }
	

}

  

原文地址:https://www.cnblogs.com/eason-d/p/8024584.html