/**
* 将数组s中的内容复制到数组d中,从from开始复制,from+i结束,发如果s数组长度不够,则补零
*
* @param d
* @param s
* @param from
* @param i
*/
public static void byteFirstCopy(byte d[], byte s[], int from, int i) {
int j;
for (j = 0; j < i; j++) {
if (j < s.length) {
d[j + from] = s[j];
} else {
d[j + from] = (byte) 0;
}
}
}
/**
* 将数组s中从from开始的maxlen个元素复制到数组d中,以0结束
*
* @param d
* @param s
* @param from
* @param maxlen
* @return
*/
public static int arrayCopy(byte d[], byte s[], int from, int maxlen) {
int i;
for (i = 0; i < maxlen; i++)
d[i + from] = s[i];
return i;
}
/**
* 将整数转换为4个字节长度的数组
*
* @param longValue
* @param arrayLen
* 字节数组长度
* @return
*/
public static byte[] long2Byte(long intValue) {
byte[] b = new byte[4];
int mark = 0xFF;//11111111
for (int i = 0; i < 4; i++) {
b[i] = (byte) (intValue >>> 8 * (3 - i) & mark);
}
return b;
}
/**
* 将整数转换成大小指定为arrayLen的字节数组,请注意value与arrayLen之间的关系,其是否存在越界。
*
* 请检查value的最大值为2的arrayLen*8次方减一,
*
* 例如:arrayLen = 1;maxValue = 2^1*8-1=255;
*
* @param value
* 整数值
* @param arrayLen
* 数组长度
* @return 该整形所对应的字节数组
*/
public static byte[] long2Byte(long value, int arrayLen) {
byte[] bytes = new byte[arrayLen];
if (arrayLen < 4) {
for (int i = 0; i < arrayLen; i++) {
bytes[i] = (byte) (value >>> 8 * (arrayLen - i - 1) & 0xFF);
}
return bytes;
}
byte[] temp = CmppTool.long2Byte(value);
CmppTool
.byteFirstCopy(bytes, temp, arrayLen - temp.length, temp.length);
return bytes;
}
/**
* 将字节数组转化成整数
*
* @param b
* 字节数组
* @return 字节数组所对应的整数
*/
public static long byte2Long(byte[] b) {
long longValue = 0, mark = 0xFF;
byte[] temp;
int multiple = 0;
if (b.length % 4 != 0) {
multiple = b.length / 4 + 1;
temp = new byte[4 * multiple];
if (b.length > 4) {
for (int i = 1; i < b.length; i++) {
temp[4 * multiple - i] = b[b.length - i];
}
} else {
for (int i = 0; i < b.length; i++) {
longValue += (b[i] & mark) << (8 * (b.length - i - 1));
}
return longValue;
}
} else {
temp = b;
}
for (int i = 0; i < temp.length; i++) {
longValue += (temp[i] & mark) << (8 * (7 - i));
}
return longValue;
}