Conversion of byte array to int type in "Go" Java (two ways)----good.

Source: Internet
Author: User

Original URL: http://blog.csdn.net/piaojun_pj/article/details/5903009

In Java, the conversion of byte array and int type, in network programming this algorithm is the most basic algorithm, we all know that in the socket transmission, the data received by the sender is a byte array, but the int type is 4 bytes, How to convert an int into a byte array, and how to convert a byte array of length 4 to the int type. There are two ways of doing this.

The first method:

public static byte[] Int2byte (int res) {

Byte[] targets = new BYTE[4];

Targets[0] = (byte) (res & 0xff);//lowest bit  
targets[1] = (byte) ((res >> 8) & 0xff);//Sub-low   ;
Targets[2] = (byte) ((res >>) & 0xff);//secondary high  
targets[3] = (byte) (res >>> 24);//Highest bit, no character Move the number to the right.  
return targets; 


public static int byte2int (byte[] res) { 
// A byte data shifted left 24 bits into 0x?? 000000, then move right 8 bits into 0x00?? 0000&NBSP

int targets = (Res[0] & 0xff) | ((Res[1] << 8) & 0xff00)//| Represents an   or a-n;
| ((res[2] <<) >>> 8) | (Res[3] <<);  
return targets; 
}

The second method:
public static byte[] Inttobytearray (int i) throws Exception {
Bytearrayoutputstream buf = new Bytearrayoutputstream ();
DataOutputStream dos= New DataOutputStream (BUF);
Dos.writeint (i);
Byte[] B = Buf.tobytearray ();
Dos.close ();
Buf.close ();
return b;
}

public static int Bytearraytoint (byte b[]) throws Exception {
int temp = 0, a=0;
Bytearrayinputstream buf = new Bytearrayinputstream (b);

DataInputStream dis= New DataInputStream (BUF);
return Dis.readint ();

}

Personal feelings The second method is more commonly used, and it is easier to implement byte arrays with other basic data types (long,float ) to convert each other.

Conversion of byte array to int type in "Go" Java (two ways)----good.

Related Article

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.