In Android development, we will encounter file transmission, which will involve data transmission. For example, if the size of a file is kb and the data type is int, and the data on the network is all byte data streams, an int-> byte [] method is required .. Let's look at a simple example.
Public class integer2byte {
Public static void main (string [] ARGs) throws exception {
Int I = 1989;
Byte [] Buf = i2b2 (I );
For (byte B: BUF ){
System. Out. Print (B + "");
}
}
// What is an algorithm used to improve performance? haha!
Public static byte [] i2b1 (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;
}
// The second method I believe you have read it, and then you can check the API.
Public static byte [] i2b2 (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;
}
}
Here, we may wonder why we need to perform operations with 0xff ?? I have read the previous materials and online materials and summarized them. I believe it will be helpful to people with poor basic knowledge.
The reason is:
1. The Byte size is 8 bits, and the int size is 32 bits.
2. the binary code of Java uses the complement form.
3.0xff is an integer by default. Therefore, a byte and 0xff will first convert the byte into an integer operation. In this way, the 24 bits in the result will always be cleared, so the results are always what we want.
Here is a simple example:
When a byte is converted to an int value, because the int value is 32 bits, and the byte value is only 8 bits,
For example, if the decimal number of the complement code 11111111 is-1 and the value is converted to int, it is changed to 11111111111111111111111111111111, that is, 0xffffffff, but this number is incorrect. Such a complement will cause an error.
And 0xff, the 24-bit high will be cleared, and the result is correct.