java中byte的大小为8bits,一个字节,是个有符号数,其范围为-128~127;int的大小为32bits。
byte与十六进制串转换的桥梁是int,先把byte转换是无符号的int(int i = b & 0xff),再通过Integer.toHexString(i)的方法转换成HexString;
HexString 通过Integer.parseInt(hexStr, 16)转换成int,然后再byte b = i转换成byte。
byte数组转化成HexString ;
public class Main{
String hexStr = "";
for(byte bb: b){
hexStr += byte2Hex(bb);
}
return hexStr;
}
private static String byte2Hex(byte b){
int i = b&0xff;
String hexStr = Integer.toHexString(i);
return hexStr.toUpperCase();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
byte[] bytes = new byte[]{-128, (byte) 0xff, 0x10, (byte) 0xCA};
String hex = bytes2Hex(bytes);
System.out.println("hex = "+ hex);
}
}
console 中输出
hex = 80FF10CA
--------------------------------------------------------------------------------------------------------
HexString转换成byte数组
public class Main{
private static byte hex2Byte(String str){
int i = Integer.parseInt(str, 16);
byte b = (byte)i;
return b;
}
private static byte[] hex2Bytes(String str){
byte[] bytes = null;
if(str.length() > 0 && str.length() % 2 == 0){
bytes = new byte[str.length()/2];
for(int i = 0; i < bytes.length; i++){
bytes[i] = hex2Byte(str.substring(2*i, 2*i+2));
}
}
return bytes;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String hexStr = "FF80FE40EF77";
byte[] bytes = hex2Bytes(hexStr);
for(byte b:bytes){
System.out.println("b = " + b);
}
String returnHex = bytes2Hex(bytes);
System.out.println("returnHex = " + returnHex);
}
}
console 中输出:
b = -1
b = -128
b = -2
b = 64
b = -17
b = 119
returnHex = FF80FE40EF77