Original URL: http://freewind886.blog.163.com/blog/static/661924642011810236100/
Recently in doing some coding and decoding related things, but also encountered the conversion of byte and int, looking at those about anti-code, the complement of instructions still headache, or write down some practical methods.
byte, int
Coercion type conversions can be used directly: byte B = (byte) aInt;
This operation is to intercept the lowest byte in int directly, and if int is greater than 255, the value becomes unrecognizable.
For an int obtained by Inputstream.read (), this method can be used to restore the value.
byte-int
There are two cases where a requirement to keep the value constant, such as a numerical calculation, can be cast with a forced type: int i = (int) abyte;
The other is to keep each bit in the lowest byte unchanged, 3 high bytes are all filled with 0, for example, to encode and decode operations,
You need to take a bitwise operation: int i = b & 0xFF;
int Inputstream.read ()
The function returns an int type, ranging from 0 to 255, and returns-1 if the end of the stream is reached. From the source of the Bytearrayinputstream, you can see how to go from byte to int
public synchronized int read () {
Return (POS < count)? (buf[pos++] & 0xff):-1;
}
int <-> byte[]
Code Transfer from:java int and byte conversions
public static byte[] Tobytearray (int iSource, int iarraylen) {
byte[] Blocalarr = new Byte[iarraylen];
for (int i = 0; (I < 4) && (I < iarraylen); i++) {
Blocalarr[i] = (byte) (ISource >> 8 * I & 0xFF);
}
return Blocalarr;
}
Converts a byte array Brefarr to an integer, and the lower byte array is the low byte bit of the integer type
public static int ToInt (byte[] brefarr) {
int ioutcome = 0;
BYTE bloop;
for (int i = 0; i < brefarr.length; i++) {
Bloop = Brefarr[i];
Ioutcome + = (bloop & 0xFF) << (8 * i);
}
return ioutcome;
}
Conversion of Byte, int in "Goto" Java