java 取int型的第二個位元組的數
阿新 • • 發佈:2019-02-01
無意中看到某個題目,前提條件,一個byte最多表示256位,因為其是由8個位表示 ,八個1 最多表示256位。
一個int由32位組成,所以是4個byte表示。題目要求是給定一個int數字,問第二個byte是多少。剛開始不會寫。
再後來複習nio時,突然想到這題。
1.首先建立 Bytebuffer,其內部是由byte組成的陣列。因為我們儲存一個int 只需要建立一個大小為4byte的即可。下面看程式碼。
public static void main(String[] args) throws IOException { ByteBuffer bb=ByteBuffer.allocate(4); //建立大小為4的byteBuffer bb.asIntBuffer().put(5566); //以int檢視將任意int數存進去 System.out.println(Arrays.toString(bb.array())); //打印出改bytebuffer,其中想要第幾個byte就取出就好了 }
結果
[0, 0, 21, -66]
2.通過位運算計算,,首先
int a=5566;
a=a>>8;
a=a&0xff;
得到的a就是 第二位的值
3.附一個int轉byte陣列
private static byte[] intToByte(int in){ byte [] b=new byte[4]; b[3]= (byte) (in&0xff); b[2]= (byte) (in>>8 &0xff); b[1]= (byte) (in>>16 &0xff); b[0]= (byte) (in>>24 &0xff); return b; }