转自百度
http://wenku.baidu.com/view/3ac0c71db7360b4c2e3f6432.html
//整数到字节数组的转换
public static byte[] intToByte(int number) {
int temp = number;
byte[] b=new byte[4];
for (int i=b.length-1;i> -1;i--){
b[i] = new Integer(temp&0xff).byteValue(); //将最高位保存在最低位
temp = temp > > 8; //向右移8位
}
return b;
}
//字节数组到整数的转换
public static int byteToInt(byte[] b) {
int s = 0;
for (int i = 0; i < 3; i++) {
if (b[i] > = 0)
s = s + b[i];
else
s = s + 256 + b[i];
s = s * 256;
}
if (b[3] > = 0) //最后一个之所以不乘,是因为可能会溢出
s = s + b[3];
else
s = s + 256 + b[3];
return s;
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
Therefore for an array of 4 bytes (buf[]), which represents an integer :
int i = 0;
int pos = 0;
i += unsignedByteToInt(buf[pos++]) << 24;
i += unsignedByteToInt(buf[pos++]) << 16;
i += unsignedByteToInt(buf[pos++]) << 8;
I += unsignedByteToInt(buf[pos++]) << 0;
To convert a byte to it's hexadecimal equivalent
public static String byteToHex(byte b){
int i = b & 0xFF;
return Integer.toHexString(i);
}