一、字符串 >> 字节数组
String s1 = "hello world";
byte[] b1 = s1.getBytes();
System.out.println(Arrays.toString(b1));
二、字节数组 >> 字符串
byte[] b1 = {
104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100};
String s1 = new String(b1);
System.out.println(s1);
三、Hex >> 字节数组
public static byte hexToByte(String inHex){
return (byte)Integer.parseInt(inHex,16);
}
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=hexToByte(inHex.substring(i,i+2));
j++;
}
return result;
}
四、字节数组 >> Hex
public static String byteToHex(byte b)
{
String hexString = Integer.toHexString(b & 0xFF);
if (hexString.length() < 2)
{
hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
}
return hexString.toUpperCase();
}
public static String bytesToHex(byte[] bytes)
{
StringBuffer sb = new StringBuffer();
if (bytes != null && bytes.length > 0)
{
for (int i = 0; i < bytes.length; i++) {
String hex = byteToHex(bytes[i]);
sb.append(hex);
}
}
return sb.toString();
}
五、Base64 >> Hex
public static String byteToHex(byte b)
{
String hexString = Integer.toHexString(b & 0xFF);
if (hexString.length() < 2)
{
hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
}
return hexString.toUpperCase();
}
public static String bytesToHex(byte[] bytes)
{
StringBuffer sb = new StringBuffer();
if (bytes != null && bytes.length > 0)
{
for (int i = 0; i < bytes.length; i++) {
String hex = byteToHex(bytes[i]);
sb.append(hex);
}
}
return sb.toString();
}
public static String base64Tohex(String bstxt){
byte[] bs = Base64.decode(bstxt);
String hex = bytesToHex(bs);
return hex.toLowerCase();
}