int i = 10; String s = String.format("%02x", i); System.out.println(s);
public static String toHexString(int i, int digits) { String format = String.format("%%0%dx", digits); String s = String.format(format, i); return s; }更泛用点
/** * 十六进制字符与数字转换表。 */ public static final String HEX_TABLE="0123456789abcdef"; /** * 将十六进制字符转换成数字。 * @param c 将转换的字符。 * @return 转换成的数字。 * @throws NotByteInfoException */ public static int StringHexToInt(char c) throws NotByteInfoException{ c=Character.toLowerCase(c); int value=HEX_TABLE.indexOf(c); if(value==-1){ throw new NotByteInfoException("必须是十六进制字符"); } return value; } /** * 将字节数组转换成十六进制的字符表现形式。 * @param b 字节数组。 * @return 十六进制字符表现形式。 */ public static String byteToString(byte[] b){ StringBuffer sb=new StringBuffer(); for (int i = 0; i < b.length; i++) { sb.append(HEX_TABLE.charAt((b[i]>>4)&0xf)).append(HEX_TABLE.charAt((b[i]>>0)&0xf)); } return sb.toString(); } /** * 将十六进制字符串转换成字节数组。 * @param str 需要转换的字符串。 * @return 字节数组。 * @throws NotByteInfoException 不是byte类型字符串 */ public static byte[] stringToByte(String str) throws NotByteInfoException{ char[] c=str.toCharArray(); byte[] b=new byte[c.length/2]; int m=0; for (int i = 0; i < c.length; i+=2) { int j=CipherTool.StringHexToInt(c[i])<<4; int k=CipherTool.StringHexToInt(c[i+1]); b[m]=(byte)(j|k); m++; } return b; } 就这些了
String s = String.format("%02x", i);
System.out.println(s);
String format = String.format("%%0%dx", digits);
String s = String.format(format, i);
return s;
}更泛用点
/**
* 十六进制字符与数字转换表。
*/
public static final String HEX_TABLE="0123456789abcdef";
/**
* 将十六进制字符转换成数字。
* @param c 将转换的字符。
* @return 转换成的数字。
* @throws NotByteInfoException
*/
public static int StringHexToInt(char c) throws NotByteInfoException{
c=Character.toLowerCase(c);
int value=HEX_TABLE.indexOf(c);
if(value==-1){
throw new NotByteInfoException("必须是十六进制字符");
}
return value;
}
/**
* 将字节数组转换成十六进制的字符表现形式。
* @param b 字节数组。
* @return 十六进制字符表现形式。
*/
public static String byteToString(byte[] b){
StringBuffer sb=new StringBuffer();
for (int i = 0; i < b.length; i++) {
sb.append(HEX_TABLE.charAt((b[i]>>4)&0xf)).append(HEX_TABLE.charAt((b[i]>>0)&0xf));
}
return sb.toString();
}
/**
* 将十六进制字符串转换成字节数组。
* @param str 需要转换的字符串。
* @return 字节数组。
* @throws NotByteInfoException 不是byte类型字符串
*/
public static byte[] stringToByte(String str) throws NotByteInfoException{
char[] c=str.toCharArray();
byte[] b=new byte[c.length/2];
int m=0;
for (int i = 0; i < c.length; i+=2) {
int j=CipherTool.StringHexToInt(c[i])<<4;
int k=CipherTool.StringHexToInt(c[i+1]);
b[m]=(byte)(j|k);
m++;
}
return b;
}
就这些了