import java.io.UnsupportedEncodingException;
/**
* byte[] 字符串 16进制 10进制 相互转换
* Created by Administrator on 2016-11-24.
*/
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "测试中文";
String str16 = encode(str, "GBK"); //中文转换为16进制字符串
System.out.println(str16);
byte[] bytes = HexToByte(str16); //16进制字符串转换为byte[]
String str162 = bytesToHexString(bytes); //byte[]转换为16进制字符串
System.out.println(str162);
System.out.println(new String(bytes, "GBK")); //byte[]转换为中文
System.out.println(decode(str16, "GBK")); //16进制字符串转换为中文
String str161 = "ef";
System.out.println(Integer.parseInt(str161, 16)); //16进制数据转换为10进制数据
}
//16进制字符串转换为byte[]
public static byte[] HexToByte(String hexString){
int len = hexString.length();
byte[] b = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
b[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16));
}
return b;
}
/**
* 16进制数字字符集
*/
private static String hexString="0123456789ABCDEF";
/**
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
public static String encode(String str, String charset) throws UnsupportedEncodingException {
//根据默认编码获取字节数组
byte[] bytes=str.getBytes(charset);
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();
}
/**
* 将16进制数字解码成字符串,适用于所有字符(包括中文)
*/
public static String decode(String bytes, String charset) throws UnsupportedEncodingException {
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(), charset);
}
/**
* byte[]转换为16进制字符串
* @param src byte[]数组
* @return String
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if ((src == null) || (src.length <= 0)) {
return null;
}
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);
}
return stringBuilder.toString();
}
//byte转为16进制字符串
public static String hexString(byte b) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
return hex;
}
//byte转int
public static int(byte b){
return b & 0xFF;
}
}