一、 byte[] 和 char[] 相互转换
1.byte[] 转 chaar[]
public static char[] bytesTochars(byte[] c,int size) {
if(c==null || c.length==0)
return null;
char[] b=new char[size];
try {
for (int i = 0; i < size; i++) {
b[i]= (char)(c[i]&0xFF);
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
2.char[] 转 byte[]
public static byte[] charsTobytes(char[] c,int size) {
if(c==null || c.length==0)
return null;
byte[] b=new byte[size];
try {
for (int i = 0; i < size; i++) {
b[i]= (byte)((int)c[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
二、十六进制 和 char[] 相互转换
1.char[]转 hex
public static String chars2HexString(char[] c, int size) {
StringBuffer sb=new StringBuffer();
try {
int j = 0;
for (int i = 0; i < size; i++) {
String hex = Integer.toHexString(c[i]);
if (hex.length() == 1) {
hex = "0" + hex;
}
sb.append(hex.toUpperCase());
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
2.hex 转char[]
public static char[] hexString2Chars(String hex) {
if(hex!=null && hex.length()>0 && hex.length()%2==0) {
hex = hex.replace(" ", "");
char[] bytes = new char[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (char) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
return null;
}
三、十六进制 和 byte[]
一、hex 转byte[]
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) Integer.parseInt(hexString.substring(pos,pos+2),16);
}
return d;
}
二、 byte[]转 hex
public static String bytes2HexString2(byte[] b, int size) {
StringBuffer sb=new StringBuffer();
try {
for (int i = 0; i < size; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
sb.append(hex.toUpperCase());
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
四、int 和 byte[]
1.int 转 byte[]
public static byte[] int2Bytes(int num) {
byte[] byteNum = new byte[4];
for (int ix = 0; ix < 4; ++ix) {
int offset = 32 - (ix + 1) * 8;
byteNum[ix] = (byte) ((num >> offset) & 0xff);
}
return byteNum;
}
2.byte[] 转int
public static int bytesToInt(byte[] bytes) {
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}