字符串轉十六進制與十六進制轉字符串示例

package stringtohex;
/**
 * java中使用16位(2個字節)的Unicode字符集編碼作爲字符編碼格式。
 * char類型的值也可直接作爲整數類型的值來使用,但它是一個16位的無符號整數,即全部是正數,範圍是0-65535
 * 如果把0-65535內的一個int整數賦給char類型變量,系統會把這個int整數當成char類型變量
 * @author AbuGe
 *
 */
public class StringToHexDemo 
{
	private static String hexString = "0123456789ABCDEF";
	public static void main(String[] args)
	{
		String s = "ab";
		//將字符串轉換成字節數組
		byte[] b = s.getBytes();
		StringBuilder sb = new StringBuilder(b.length * 2);
		//將字節數組中的每個字節拆分成兩個16進制數
		for(int i = 0; i < b.length; i++)
		{
			sb.append(hexString.charAt((b[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((b[i] & 0x0f) >> 0));
		}
		String hexStr = sb.toString();
		//注意一個char字符型佔兩個字節
		byte[] c = convert2HexArray(s);
		for(int i = 0; i < c.length; i++)
		System.out.println(c[i]);
		
	}
	//字符串轉化爲十六進制表示,字符串只能是01234567890abcdef,否則會拋出java.lang.NumberFormatException
	  private static byte[] convert2HexArray(String apdu) 
	    {
	          int len = apdu.length() / 2;
	  	      char[] chars = apdu.toCharArray();
	  	      String[] hexes = new String[len];
	  	      byte[] bytes = new byte[len];
	  	      for (int i = 0, j = 0; j < len; i = i + 2, j++)
	  	      {
	  	          hexes[j] =""+chars[i]+chars[i+1];//兩個字符組成一個字節
	  	          bytes[j] = (byte)Integer.parseInt(hexes[j],16);
	  	      }
	  	      return bytes;
	      }
	//十六進制轉化爲字符串
	  public static String byte2hex(byte[] b) 
	    { //一個字節的數, 轉成16進制字符串
	        String hs = "";
	        String tmp = "";
	        for (int n = 0; n < b.length; n++) 
	        {
	            //整數轉成十六進制表示
	            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
	            if (tmp.length() == 1) 
	            {
	                hs = hs + "0" + tmp;
	            } else {
	                hs = hs + tmp;
	            }
	        }
	        tmp = null;
	        return hs.toUpperCase(); //轉成大寫
	    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章