JAVA byte[]、十六进制字符串、整形(Long、int)数据类型之间的转换
在编程中我们经常遇到数据类型之间的转换,现在我们来总结一下,有更好的请大家共享指导:
- 十六进制字符串数据 转 byte[]
- byte[] 转 十六进制字符串
- byte[] 转 int
- *int 转 byte[]
- byte[] 转 Long
- Long 转 byte[]
十六进制字符串数据 转 byte[]
/**
* 16进制字符串转byte
* @param strIn
* @return
* @throws Exception
*/
public static byte[] hexStr2ByteArr(String strIn) {
try {
if (strIn==null)return null;
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
byte[] arrOut = new byte[iLen/2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
byte[] 转 十六进制字符串
/**
* 16进制的形式输出
* @param b
* @return
*/
public static String byte2HexStr(byte[] b){
String stmp="";
StringBuilder sb = new StringBuilder("");
try {
for (int n=0;n<b.length;n++)
{
stmp = Integer.toHexString(b[n] & 0xFF);
sb.append((stmp.length()==1)? "0"+stmp : stmp);
//sb.append(" ");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString().toUpperCase().trim();
}
byte[] 转 int
/**
* byte装成int
* @param value
* @return
*/
public static int bytesToint(byte[] value) {
int ret = 0;
for (int i = 0; i < value.length; i++) {
ret += (value[value.length - i - 1] & 0xFF) << (i * 8);
}
return ret;
}
int 转 byte[]
/**
* 转成字节长度
* @param iSource 原数据
* @param iArrayLen 输出数据
* 只能转整形最多4个字节
* @return
*/
public static byte[] toByteArray(int iSource, int iArrayLen) {
byte[] bLocalArr = new byte[iArrayLen];
for (int i = 0; (i < 4) && (i < iArrayLen); i++) {
bLocalArr[i] = (byte) (iSource >> 8 * i & 0xFF);
}
byte temp;
int len = bLocalArr.length;
for (int i = 0; i < len / 2; i++) {
temp = bLocalArr[i];
bLocalArr[i] = bLocalArr[len - 1 - i];
bLocalArr[len - 1 - i] = temp;
}
return bLocalArr;
}
byte[] 转 Long
/**
* byte[] 转 Long
* @return
*/
public static long bytesToLong(byte[] value) {
long ret = 0;
for (int i = 0; i < value.length; i++) {
ret += (long) (value[value.length - i - 1] & 0xFF) << (long) (i * 8);
}
return ret;
}
Long 转 byte[]
/**
* Long 转 byte[]
* @return
*/
public static byte[] longTobytes(long val) {
int length = 8;
byte[] value = new byte[length];
for (int i = 0; i < length; i++)
value[length - i - 1] = (byte) (val >> i * 8);
return value;
}