Java int 与 byte的转换 & 0xFFjava
采用强制类型转换 byte 类型的取值范围是 -128~127。当把int转换成byte时,超出这个范围,值就不会相等。数组
int ii = 128; byte bb = (byte) ii; System.out.println(ii == bb); //false int iii = 127; byte bbb = (byte) iii; System.out.println(iii == bbb);//true
经过InputStream的read()方法获取的int,可采用强制类型转换将值还原为byte类型,ide
/** * Reads the next byte of data from the input stream. The value byte is * returned as an <code>int</code> in the range <code>0</code> to * <code>255</code>. If no byte is available because the end of the stream * has been reached, the value <code>-1</code> is returned. This method * blocks until input data is available, the end of the stream is detected, * or an exception is thrown. * * <p> A subclass must provide an implementation of this method. * * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached. * @exception IOException if an I/O error occurs. */ public abstract int read() throws IOException;
注意这个int 值的范围是 0~255,转换成byte,不会超出byte的位的长度。oop
这里有两种状况,一种是要求保持值不变,例如进行数值计算,可采用强制类型转换:int i = (int) aByte; 另外一种是要求保持最低字节中各个位不变,3个高字节所有用0填充,例如进行编解码操做, 则须要采用位操做:int i = b & 0xff;this
经过ByteArrayInputStream的read()方法,经过位操做将byte转换为int,spa
/** * Reads the next byte of data from this input stream. The value * byte is returned as an <code>int</code> in the range * <code>0</code> to <code>255</code>. If no byte is available * because the end of the stream has been reached, the value * <code>-1</code> is returned. * <p> * This <code>read</code> method * cannot block. * * @return the next byte of data, or <code>-1</code> if the end of the * stream has been reached. */ public synchronized int read() { return (pos < count) ? (buf[pos++] & 0xff) : -1; }
public class Transfer { 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) (0xFF & (iSource >>> (i << 3))); } return bLocalArr; } 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) << (i << 3); } return iOutcome; } public static void main(String args[]) { int a = 100; byte[] arr = toByteArray(a, 4); int b = toInt(arr); System.out.println(b); } }
以这个为例,code
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) (0xFF & (iSource >>> (i << 3))); } return bLocalArr; }
int类型在java中用8个字节32位来表示,byte类型为一个字节8位。咱们要作的就是将32位分四次,每次获取8位写入到字节数组中。首先是低8位,和0xFF相与后,高24比特就会被置为0了,写入到字节数组中。而后获取后边的8位,首先要移位,无符号右移8位,和0xFF相与后,保留8位,把这八位写入到数组中。后边依次类推。最终完整的把int写入到字节数组中。input
=========END=========io