Android int to byte [] method, androidbyte

Source: Internet
Author: User

Android int to byte [] method, androidbyte
/**
* Convert basic data types to byte arrays and reverse conversion methods
* Only the conversion operation is involved, and the parameter is not verified.
* Applicability: RMS operations and Network Data Transmission
*/
Public class DataConvert {
/**
* Convert int type data to byte array
* @ Param n int data
* @ Return: byte array generated
*/
Public static byte [] intToBytes (int n ){
String s = String. valueOf (n );
Return s. getBytes ();
}
 
/**
* Convert byte array to int data
* @ Param B byte array
* @ Return: int data generated
*/
Public static int bytesToInt (byte [] B ){
String s = new String (B );
Return Integer. parseInt (s );
}
 
/**
* Convert int type data to byte array
* Principle: extract four bytes from the int data and store them separately.
* @ Param n int data
* @ Return: byte array generated
*/
Public static byte [] intToBytes2 (int n ){
Byte [] B = new byte [4];
For (int I = 0; I <4; I ++ ){
B [I] = (byte) (n> (24-I * 8 ));
}
Return B;
}
 
/**
* Convert byte array to int data
* @ Param B byte array
* @ Return: int data generated
*/
Public static int byteToInt2 (byte [] B ){
Return (int) B [0]) <24) + (int) B [1]) <16) + (int) B [2]) <8) + B [3];
}
}
In C #, how do I convert an int to a byte [] with a 4-length?

Public static byte [] intToByte4 (int Num ){
Byte [] abyte = new byte [8]; // int Is 32-bit, except 4-bit, And the array is 8
Int j = 0xf;
Int z = 4; // Number of converted digits
For (int I = 0; I <8; I ++)
{
Int y = j <z * I;
Int x = Num & y;
X = x> (z * I );
Abyte [I] = (byte) (x );
}

Return abyte ;}

How to convert int to byte in java

Byte [] byteArray = new byte [4];
For (int n = 0; n <byteNum; n ++)
ByteArray [3-n] = (byte) (integer >>> (n * 8 ));
Return (byteArray );
}

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.