public class Intbyte {
public static int byte2int(byte[] byt){
return (int)(byt[0]&0xff | (byt[1]&0xff)<<8 | (byt[2]&0xff)<<16 | (byt[3]&0xff)<<24);
}
public static byte[] int2byte(int number){
byte[] byt = new byte[4];
byt[0] = (byte)(number&0xff);
byt[1] = (byte)(number>>8&0xff);
byt[2] = (byte)(number>>16&0xff);
byt[3] = (byte)(number>>24&0xff);
return byt;
}
public static void main(String args[]){
System.out.println(byte2int(int2byte(-345)));
}
}
整型占32位字符,表现形式为:
10101010 00000000 11111010 00001111
字节型只占一个8个字符(一个字节)
00000000 00000000 00000000 10100101
10&0xff 其实就是
00000000 00000000 00000000 00001010
00000000 00000000 00000000 11111111 (“与”运算)
----------------------------------------------------------------------------
00000000 00000000 00000000 00001010 因此保留了最小的几位
(10&0xff)<<8 是因为移位运算符 优先级高。
实现的功能就是:
00000000 00000000 00000000 00001010 (左移8位)
-----------------------------------------------------------------------------
00000000 00000000 00001010 00000000 (移位后的结果)