java int to byte and long to byte _java

Source: Internet
Author: User

In network programming, it is often necessary to process long and int in a native way, rather than to string, for bandwidth savings or coding purposes.

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--) {//from the tail of B (that is, the low of int value) Start copy data if (J >= 0) A[i] = B[j]; else A[i] = 0;//If b.length is less than 4, the high 0} int v0 = (a[0] & 0xff) << 24;//&0xff converts the byte value to an int without any difference, avoiding the Java automatic type elevation 
Reserved high level sign bit 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; }

}

The above is the small series for everyone to bring the Java int to byte and long to byte of the whole content of the method, I hope that we support cloud-Habitat Community ~

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.