1. Storage size: int is 32 bits, byte is 8 bits, so 4 bytes are used to dump
Example:
byte[0] records 8-1 bits;
byte[1] records 16-9 bits;
byte[2] records 24-17 bits;
byte[3] records 32-25 bits;
2. When int is directly converted to byte, the lower 8 bits are stored. Therefore, to completely record 32-1 bits, the int type needs to be shifted between 32-9 bits, and it can be moved to 8-1 bits.
Example:
byte[0] records 8—1 bit—does not move—> b[0] = (byte) int;
byte[1] records 16—9 bits——shift right by 8 bits——> b[1] = (byte) (int >> 8);
byte[2] records 24-17 bits--shift right by 16 bits--> b[2] = (byte) (int >> 16);
byte[3] record 32-25 bits——shift right by 24 bits—>b[3] = (byte) (int >> 24);
3. If you want to convert a negative int to byte, you must consider: the sign bit after shifting. After shifting, if the int type variable is a negative number before the int is forced to byte, the high bit (sign bit) needs to be processed with &0xff.
Example:
byte[0] records 8—1 bit—does not move—> b[0] = (byte) int;
1. When converting byte[] to int type, the code was not written correctly, and unexpected gains were found
//错误写法:少写了 &0xff//发现在(0,127)之间结果正确publicstaticintbyteArrayToInt(byte[] bytes){
int value=0;for(int i =0; i <4; i++){
value += bytes[i]<<(3-i)*8;}return value;}//错误写法:(bytes[i] & 0xff) 少了()//发现在(0,255)之间结果正确publicstaticintbyteArrayToInt(byte[] bytes){
int value=0;for(int i =0; i <4; i++){
value += bytes[i]&0xff<<(3-i)*8;}return value;}