java int to byte and long to byte

  • 2020-05-10 18:07:51
  • OfStack

In network programming, long and int are usually handled natively, rather than converted to string, for reasons of bandwidth savings or coding needs.


public class ByteOrderUtils {

public static byte[] int2byte(int res) { 
byte[] targets = new byte[4]; 

targets[3] = (byte) (res & 0xff);//  Its lowest  
targets[2] = (byte) ((res >> 8) & 0xff);//  A low  
targets[1] = (byte) ((res >> 16) & 0xff);//  Time high  
targets[0] = (byte) (res >>> 24);//  highest , Unsigned right shift.  
return targets; 
}

public static int byteArrayToInt(byte[] b){ 
byte[] a = new byte[4]; 
int i = a.length - 1,j = b.length - 1; 
for (; i >= 0 ; i--,j--) {// from b The tail of the ( namely int The value of the low ) start copy data  
if(j >= 0) 
a[i] = b[j]; 
else 
a[i] = 0;// if b.length insufficient 4, Will be high fill 0 
} 
int v0 = (a[0] & 0xff) << 24;//&0xff will byte No difference in value is converted into int, avoid Java After automatic type promotion , The high bit of the symbol is preserved  
int v1 = (a[1] & 0xff) << 16; 
int v2 = (a[2] & 0xff) << 8; 
int v3 = (a[3] & 0xff) ; 
return v0 + v1 + v2 + v3; 
}

public static byte[] long2byte(long res) { 
byte[] buffer = new byte[8]; 
for (int i = 0; i < 8; i++) { 
int offset = 64 - (i + 1) * 8; 
buffer[i] = (byte) ((res >> offset) & 0xff); 
}
return buffer;
}

public static long byteArrayToLong(byte[] b){ 
long values = 0; 
for (int i = 0; i < 8; i++) { 
values <<= 8; values|= (b[i] & 0xff); 
} 
return values; 
}

}

Related articles: