Java int to byte and long to byte, intbyte

Source: Internet
Author: User

Java int to byte and long to byte, intbyte

In network programming, to save bandwidth or coding, you usually need to process long and int in native mode instead of converting to string.

Public class ByteOrderUtils {

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

Targets [3] = (byte) (res & 0xff); // second bit
Targets [2] = (byte) (res> 8) & 0xff); // low position
Targets [1] = (byte) (res> 16) & 0xff); // high
Targets [0] = (byte) (res >>> 24); // highest bit, unsigned shifted to the right.
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 --) {// copy data from the end of B (that is, the low position of the int value)
If (j> = 0)
A [I] = B [j];
Else
A [I] = 0; // If B. length is less than 4, the high value is 0.
}
Int v0 = (a [0] & 0xff) <24; // & 0xff converts the byte value to an int value without any difference. This prevents the high sign bit from being retained after the Java automatic type upgrade.
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;
}

}

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.