java int to byte and long to byte

Source: Internet
Author: User

In network programming, in order to conserve bandwidth or coding needs, it is often necessary to process long and int in the native way, instead of converting to string.

public class Byteorderutils {

public static byte[] Int2byte (int res) {
Byte[] targets = new BYTE[4];

TARGETS[3] = (byte) (res & 0xff);//Lowest bit
TARGETS[2] = (byte) ((res >> 8) & 0xff);//Sub-low
TARGETS[1] = (byte) ((res >>) & 0xff);//Secondary high
Targets[0] = (byte) (res >>> 24);//highest bit, 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--) {//Start copy data from the tail of B (that is, the low of the int value)
if (J >= 0)
A[i] = B[j];
Else
A[i] = 0;//If b.length is less than 4, the high will be 0
}
int v0 = (a[0] & 0xff) << 24;//&0xff converts the byte value to int, avoids the high sign bit after the Java automatic type promotion.
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 =-(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;
}

}

java int to byte and long to byte

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.