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;
}
}