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