java中byte陣列與int型別的轉換(兩種方式)
阿新 • • 發佈:2018-12-24
java中byte陣列與int型別的轉換,在網路程式設計中這個演算法是最基本的演算法,我們都知道,在socket傳輸中,傳送、者接收的資料都是 byte陣列,但是int型別是4個byte組成的,如何把一個整形int轉換成byte陣列,同時如何把一個長度為4的byte陣列轉換為int型別。下面有兩種方式。
- publicstaticbyte[] int2byte(int res) {
- byte[] targets = newbyte[4];
- targets[0] = (byte) (res & 0xff);// 最低位
-
targets[1] = (byte) ((res >>
- targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
- targets[3] = (byte) (res >>> 24);// 最高位,無符號右移。
- return targets;
- }
- publicstaticint byte2int(byte[] res) {
- // 一個byte資料左移24位變成0x??000000,再右移8位變成0x00??0000
-
int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或
- | ((res[2] << 24) >>> 8) | (res[3] << 24);
- return targets;
- }
第二種
- publicstaticvoid main(String[] args) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(baos);
- try {
-
dos.writeByte(4
- dos.writeByte(1);
- dos.writeByte(1);
- dos.writeShort(217);
- } catch (IOException e) {
- e.printStackTrace();
- }
- byte[] aa = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- DataInputStream dis = new DataInputStream(bais);
- try {
- System.out.println(dis.readByte());
- System.out.println(dis.readByte());
- System.out.println(dis.readByte());
- System.out.println(dis.readShort());
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- dos.close();
- dis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }