JAVA基础进制转换

进制转换问题

Integer.toString(target_i, 16);就是十六进制,
Integer.toString(target_i, 2);就是二进制,
Integer.toString(target_i, 8);就是八进制,
Long,Float 也具有同样的方法



// 16进制到2进制
int Integer.decode("0xFF");
---------------------------------------------------
// 转化字符串为十六进制编码

public static String toHexString(String s)   
{   
  String str="";   
  for (int i=0;i<s.length();i++)   
  {   
    int ch = (int)s.charAt(i);   
    String s4 = Integer.toHexString(ch);   
    str = str + s4; 
   }   
   return str;   
} 



// 字符串16进制,互转
private static String hexString="0123456789ABCDEF"; 
public static String decode(String bytes) 
	{ 
		ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2); 
		//将每2位16进制整数组装成一个字节 
		for(int i=0;i<bytes.length();i+=2) 
		{
			baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1)))); 
		}
		return new String(baos.toByteArray());
	}
	 public static String encode(String str) 
	 { 
		//根据默认编码获取字节数组 
		byte[] bytes=str.getBytes(); 
		StringBuilder sb=new StringBuilder(bytes.length*2); 
		//将字节数组中每个字节拆解成2位16进制整数 
		for(int i=0;i<bytes.length;i++) 
		{ 
		sb.append(hexString.charAt((bytes[i]&0xf0)>>4)); 
		sb.append(hexString.charAt((bytes[i]&0x0f)>>0)); 
		} 
		return sb.toString(); 
	 }




// byte[] 数组转换为16进制字符串

public static void toHex(byte[] src)
	{    
	    StringBuilder stringBuilder = new StringBuilder("");    
	    if (src == null || src.length <= 0) {    
	        return ;
	    }   
	    for (int i = 0; i < src.length; i++) {    
	        int v = src[i] & 0xFF;    
	        String hv = Integer.toHexString(v);   
	        if (hv.length() < 2) {    
	            stringBuilder.append(0);    
	        }   
	        stringBuilder.append(hv);   
	    }   
	   System.out.println(stringBuilder.toString());
	}   



// 该方法测试各种编码格式,生成的16进制,位数是不同的·
public static void encode() 
	{ 
        String name = "I am 泰山"; 
        
        try { 
            byte[] iso8859 = name.getBytes("ISO-8859-1"); 
            toHex(iso8859); 
            byte[] gb2312 = name.getBytes("GB2312"); 
            toHex(gb2312); 
            byte[] gbk = name.getBytes("GBK"); 
            toHex(gbk); 
            byte[] utf16 = name.getBytes("UTF-16"); 
            toHex(utf16); 
            byte[] utf8 = name.getBytes("UTF-8"); 
            toHex(utf8); 
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
        } 
   } 


结果如下:
4920616d203f3f
4920616d20cca9c9bd
4920616d20cca9c9bd
feff004900200061006d00206cf05c71
4920616d20e6b3b0e5b1b1

你可能感兴趣的:(java基础)