Java bytea 轉二進制字元串,十六進制字元串的互相轉換
import java.io.UnsupportedEncodingException;
public class HexConver {
public static void main(String[] args) throws UnsupportedEncodingException {
String content = "嚴";
System.out.println("原字元串:" + content);
String hex2Str = conver2HexStr(content.getBytes());
System.out.println("\n二進制的表示形式:" + hex2Str);
byte[] b = conver2HexToByte(hex2Str);
System.out.println("二進制字元串還原:" + new String(b));
String hex16Str = conver16HexStr(content.getBytes());
System.out.println("\n十六進制的表示形式:" + hex16Str);
System.out.println("十六進制字元串還原:" + new String(conver16HexToByte(hex16Str),"utf-8"));
String hex16Str2 = conver16HexStr(content.getBytes("Unicode"));
System.out.println("\n十六進制的Unicode表示形式:" + hex16Str2);
System.out.println("十六進制字元串還原:" + new String(conver16HexToByte(hex16Str2),"Unicode"));
}
/**
* byte數組轉換為二進制字元串,每個位元組以","隔開
**/
public static String conver2HexStr(byte[] b) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < b.length; i++) {
result.append(Long.toString(b[i] & 0xff, 2) + ",");
}
return result.toString().substring(0, result.length() - 1);
}
/**
* 二進制字元串轉換為byte數組,每個位元組以","隔開
**/
public static byte[] conver2HexToByte(String hex2Str) {
String[] temp = hex2Str.split(",");
byte[] b = new byte[temp.length];
for (int i = 0; i < b.length; i++) {
b[i] = Long.valueOf(temp[i], 2).byteValue();
}
return b;
}
/**
* byte數組轉換為十六進制的字元串
**/
public static String conver16HexStr(byte[] b) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < b.length; i++) {
if ((b[i] & 0xff) < 0x10)
result.append("0");
result.append(Long.toString(b[i] & 0xff, 16));
}
return result.toString().toUpperCase();
}
/**
* 十六進制的字元串轉換為byte數組
**/
public static byte[] conver16HexToByte(String hex16Str) {
char[] c = hex16Str.toCharArray();
byte[] b = new byte[c.length / 2];
for (int i = 0; i < b.length; i++) {
int pos = i * 2;
b[i] = (byte) ("0123456789ABCDEF".indexOf(c[pos]) << 4 | "0123456789ABCDEF".indexOf(c[pos + 1]));
}
return b;
}
}