In Java, byte to int, javabyte to int

Source: Internet
Author: User

In Java, byte to int, javabyte to int

There are two cases for converting byte to int:

1) Keep the value unchanged

Application scenarios: numerical computing, and so on.

Method: You can directly use forced type conversion: int I = (int) aByte,

For example, if aByte = 0xff (that is, the value is-1), it is converted to int, I is 0 xffffffff, and the value is still-1.


2) Keep each bit of the lowest byte unchanged, and fill all three high bytes with 0

Application scenarios: codec operations,

Method: Bit operation: int I = aByte & 0xff,

For example, if aByte = 0xff is converted to int, I is 0x000000ff.


How to convert an int value to a byte value in java

In java, the int type occupies 4 bytes, while the byte type occupies 1 byte, So bit loss occurs when the int type is converted to the byte type, that is, the lower 8 bits of int are used as byte values. The value of the int type variable is 257, the corresponding binary value is 100000001, the last 8 digits is 00000001, and the first 0 represents the symbol bit, indicating the positive number, so the value of the variable x is 1.

Conversion between int and byte [4] in java

Import java. io .*;

Public class IOTest {
Public static void main (String [] args) throws Exception {
Int I = 65535;
Byte [] B = intToByteArray1 (I );
For (byte bb: B ){
System. out. print (bb + "");
}
}

Public static byte [] intToByteArray1 (int I ){
Byte [] result = new byte [4];
Result [0] = (byte) (I> 24) & 0xFF );
Result [1] = (byte) (I> 16) & 0xFF );
Result [2] = (byte) (I> 8) & 0xFF );
Result [3] = (byte) (I & 0xFF );
Return result;
}

Public static byte [] intToByteArray2 (int I) throws Exception {
ByteArrayOutputStream buf = new ByteArrayOutputStream ();
DataOutputStream out = new DataOutputStream (buf );
Out. writeInt (I );
Byte [] B = buf. toByteArray ();
Out. close ();
Buf. close ();
Return B;
}
}

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.