How to convert int into byte[] in Android

Source: Internet
Author: User

/**
* Convert the base data type to a byte array, and the method of reverse conversion
* Only involves conversion operations, no validation for parameters
* Applicable scope: RMS operation, network data transmission
 */
Public class dataconvert{
 /**
* Convert data of type int to byte array
* @param n int Data
* @return-generated byte array
  */
Public Static byte[] Inttobytes (int n) {
String s = string.valueof (n);
return s.getbytes ();
 }
 
 /**
* Converts a byte array to int data
* @param B-byte array
* @return the generated int data
  */
public static int bytestoint (byte[] b) {
string s = new string (b);
return Integer.parseint (s);
 }
 
 /**
* Convert data of type int to byte array
* Principle: four bytes in int data are taken out and stored separately
* @param n int Data
* @return-generated byte array
  */
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;
 }
 
 /**
* Converts a byte array to int data
* @param B-byte array
* @return the generated int data
  */
public static int ByteToInt2 (byte[] b) {
return (((int) b[0]) << + (((int) b[1]) << + (((int) b[2]) << 8) + b[3];
 }
}

How to convert int into byte[] in Android

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.