Byte array and INT Conversion

Source: Internet
Author: User

After converting the int type into a byte array in C #, it is stored in descending order, while in C ++ and Java, It is sorted in descending order, as a result, an error occurs when the converted byte array is directly communicated with C ++ or Java. It needs to be reversed and then transmitted.

Convert byte to int code

C # The conversion code is as follows:

C #
Byte [] bytes = {0, 0, 0, 25}; // if the system architecture is little-Endian (that is, little end first ), // reverse the byte array. if (bitconverter. islittleendian) // specifies the endian settings for determining the computer structure. reverse (bytes); // converts and sorts int I = bitconverter. toint32 (bytes, 0); console. writeline ("int: {0}", I); // output: INT: 25
The bitconverter. islittleendian field indicates the byte sequence ("endian") of data stored in this computer structure ).

If the structure is little-Endian, the value isTrueIf the structure is big-Endian, the value isFalse.

Different computer structures use different bytes to store data. "Big-Endian" indicates that the maximum valid byte is on the left side of the word. "Little-Endian" indicates that the maximum valid byte is on the right of the word.

 Convert int to byte code

C # The conversion code is as follows:

Byte [] AA = bitconverter. getbytes (1243 );
If (bitconverter. islittleendian)
Array. Reverse (AA );

 

The Java conversion code is as follows:

Public byte [] int2bytes (int A, Boolean ishighfirst)
{
Byte [] result = new byte [4];

If (ishighfirst)
{
Result [0] = (byte) (a> 24 & 0xff );
Result [1] = (byte) (a> 16 & 0xff );
Result [2] = (byte) (a> 8 & 0xff );
Result [3] = (byte) (A & 0xff );
}
Else
{
Result [3] = (byte) (a> 24 & 0xff );
Result [2] = (byte) (a> 16 & 0xff );
Result [1] = (byte) (a> 8 & 0xff );
Result [0] = (byte) (A & 0xff );
}
Return result;
}

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.