byte数组和int,long之间的互相转换
public static long byteToLong(byte[] value) {
long temp = 0;
for (int i = 0; i < value.length; i++) {
temp = (temp | value[i]) << 8;
}
return temp;
}
long temp = 0;
for (int i = 0; i < value.length; i++) {
temp = (temp | value[i]) << 8;
}
return temp;
}
public static byte[] longToByte(long number) {
long temp = number;
byte[] b = new byte[8];
for (int i = b.length - 1; i >= 0; i--) {
b[i] = Long.valueOf(temp & 0xff).byteValue();// 将最低位保存在最高位
temp = temp >> 8; // 向右移8位
}
return b;
}
public static byte[] intToByte(int number) {
int temp = number;
byte[] b = new byte[4];
for (int i = b.length - 1; i >= 0; i--) {
b[i] = Integer.valueOf(temp & 0xff).byteValue();// 将最低位保存在最高位
temp = temp >> 8; // 向右移8位
}
return b;
}
public static long byteToLong(byte[] value) {
long temp = 0;
for (int i = 0; i < value.length; i++) {
temp = (temp | value[i]) << 8;
}
return temp;
}
long temp = number;
byte[] b = new byte[8];
for (int i = b.length - 1; i >= 0; i--) {
b[i] = Long.valueOf(temp & 0xff).byteValue();// 将最低位保存在最高位
temp = temp >> 8; // 向右移8位
}
return b;
}
public static byte[] intToByte(int number) {
int temp = number;
byte[] b = new byte[4];
for (int i = b.length - 1; i >= 0; i--) {
b[i] = Integer.valueOf(temp & 0xff).byteValue();// 将最低位保存在最高位
temp = temp >> 8; // 向右移8位
}
return b;
}
public static long byteToLong(byte[] value) {
long temp = 0;
for (int i = 0; i < value.length; i++) {
temp = (temp | value[i]) << 8;
}
return temp;
}
/**
* byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
*
* @param src
* byte数组
* @param offset
* 从数组的第offset位开始
* @return int数值
*/
public static int bytesToInt(byte[] src, int offset) {
int value;
value = (int) ((src[offset] & 0xFF)
| ((src[offset+1] & 0xFF)<<8)
| ((src[offset+2] & 0xFF)<<16)
| ((src[offset+3] & 0xFF)<<24)); return value;
}
- /**
- * byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用
- */
- public static int bytesToInt2(byte[] src, int offset) {
- int value;
- value = (int) ( ((src[offset] & 0xFF)<<24)
- |((src[offset+1] & 0xFF)<<16)
- |((src[offset+2] & 0xFF)<<8)
- |(src[offset+3] & 0xFF));
- return value; }
-
public static byte[] intToByte4(int Num)
-
{
-
byte[] abyte=new byte[8]; //int为32位除4位,数组为8
-
int j=0xf;
-
int z = 4; //转换的位数
-
for (int i = 0; i < 8; i++)
-
{
-
int y = j << z * i;
-
int x = Num & y;
-
x = x >> (z * i);
-
abyte[i] = (byte)(x);
-
}
-
return abyte;
-
}