Home > 类库下载 > java类库 > body text

java int to byte and long to byte

高洛峰
Release: 2016-10-08 13:40:23
Original
2111 people have browsed it

<br/>
Copy after login
Copy after login

In network programming, due to the need to save bandwidth or encoding, it is usually necessary to process long and int natively instead of converting to string.

public class ByteOrderUtils {

public static byte[] int2byte(int res) { <br/>byte[] targets = new byte[4]; <br/><br/>targets[3] = (byte) (res & 0xff); // lowest Bit <br/>targets[2] = (byte) ((res >> 8) & 0xff);// Second low bit <br/>targets[1] = (byte) ((res >> 16) & 0xff);/ / Second highest bit <br/>targets[0] = (byte) (res >>> 24); // Highest bit, unsigned right shift. <br/>return targets; <br/>}

public static int byteArrayToInt(byte[] b){ <br/>byte[] a = new byte[4]; <br/>int i = a.length - 1,j = b.length - 1; <br/> for (; i >= 0 ; i--,j--) {//Copy data starting from the tail of b (that is, the low bit of the int value) <br/>if(j >= 0) <br/>a[i] = b [j]; <br/>else <br/>a[i] = 0;//If b.length is less than 4, fill the high bit with 0 <br/>} <br/>int v0 = (a[0] & 0xff) << 24;// &0xff converts the byte value into int without any difference to avoid Java's automatic type promotion and retain the high-order sign bit <br/>int v1 = (a[1] & 0xff) << 16; <br/>int v2 = (a[2] & 0xff) << 8; <br/>int v3 = (a[3] & 0xff) ; <br/>return v0 + v1 + v2 + v3; <br/>}<br/><br/>public static byte[] long2byte(long res) { <br/>byte[ ] buffer = new byte[8]; <br/>for (int i = 0; i < 8; i++) { <br/>int offset = 64 - (i + 1) * 8; <br/>buffer[i] = (byte) (( res >> offset) & 0xff); <br/>}<br/>return buffer;<br/>}

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

}

<br/>
Copy after login
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template