public class BytesUtil {
/**
* 数组合并,按顺序合并
*
* @param bs
* @return
*/
public static byte[] bytesAppend(byte[]... bs) {
int len = 0;
for (int i = 0; i < bs.length; i++) {
if (null == bs[i])
continue;
len += bs[i].length;
}
byte[] result = new byte[len];
int index = 0;
for (int i = 0; i < bs.length; i++) {
if (null == bs[i])
continue;
System.arraycopy(bs[i], 0, result, index, bs[i].length);
index += bs[i].length;
}
return result;
}
/**
* 将byte[]装换成long
*
* @param bts 最大有效位,8位
* @return
*/
public static long convert2Long(byte[] bts) {
if (bts.length > 8) {
try {
throw new Exception("溢出,long型指定数值为8个字节");
} catch (Exception e) {
e.printStackTrace();
}
}
long len = 0;
long base = 256;
for (int i = bts.length - 1, j = 0; i >= 0; i--, j++) {
int temp = ((int) bts[i]);
temp = temp < 0 ? temp + 256 : temp;
if (j == 0) {
len += temp;
} else {
len += temp * base;
base *= 256;
}
}
return len;
}
/**
* 数组装换成字符串
*
* @param fieldData
* @return
*/
public static String bytes2Str(byte[] fieldData) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < fieldData.length; i++) {
sb.append(fieldData[i] + ",");
}
return sb.substring(0, sb.length() - 1).toString();
}
/**
* 字节数组转化成二进制字符串
*
* @param str
*/
public static String bytes2BitStr(byte[] bytes) {
StringBuffer sb = new StringBuffer();
String sSingleString = "";
for (int i = 0; i < bytes.length; i++) {
sSingleString = Integer.toBinaryString(bytes[i]);
sSingleString = ("00000000" + sSingleString).substring(sSingleString.length(), sSingleString.length() + 8);
sb.append(sSingleString);
}
return sb.toString();
}
/**
* byte数组转换成16进制显示
*
* @param bs
* @return
*/
public static String bytes2HexStr(byte[] bs) {
StringBuilder stringBuilder = new StringBuilder("");
if (bs == null || bs.length <= 0) {
return null;
}
for (int i = 0; i < bs.length; i++) {
int v = bs[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
}