java中byte数组与int类型的转换(两种方式)

来源:互联网 发布:abb机器人仿真软件 编辑:程序博客网 时间:2024/05/10 04:47

转:http://blog.csdn.net/zhouyong0/article/details/8078619


java中byte数组与int类型的转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送、者接收的数据都是 byte数组,但是int类型是4个byte组成的,如何把一个整形int转换成byte数组,同时如何把一个长度为4的byte数组转换为int类型。下面有两种方式。

 

[java] view plaincopy
  1. public static byte[] int2byte(int res) {  
  2. byte[] targets = new byte[4];  
  3.   
  4. targets[0] = (byte) (res & 0xff);// 最低位   
  5. targets[1] = (byte) ((res >> 8) & 0xff);// 次低位   
  6. targets[2] = (byte) ((res >> 16) & 0xff);// 次高位   
  7. targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。   
  8. return targets;   
  9. }   
[java] view plaincopy
  1. public static int byte2int(byte[] res) {   
  2. // 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000   
  3.   
  4. int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00// | 表示安位或   
  5. | ((res[2] << 24) >>> 8) | (res[3] << 24);   
  6. return targets;   
  7. }   

第二种

[java] view plaincopy
  1. public static void main(String[] args) {    
  2.         ByteArrayOutputStream baos = new ByteArrayOutputStream();    
  3.         DataOutputStream dos = new DataOutputStream(baos);    
  4.         try {    
  5.             dos.writeByte(4);    
  6.             dos.writeByte(1);    
  7.             dos.writeByte(1);    
  8.             dos.writeShort(217);    
  9.           } catch (IOException e) {    
  10.         e.printStackTrace();    
  11.     }    
  12.     
  13.     byte[] aa = baos.toByteArray();    
  14.     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());    
  15.     DataInputStream dis = new DataInputStream(bais);    
  16.     
  17.     try {    
  18.         System.out.println(dis.readByte());    
  19.         System.out.println(dis.readByte());    
  20.         System.out.println(dis.readByte());    
  21.         System.out.println(dis.readShort());    
  22.     } catch (IOException e) {    
  23.         e.printStackTrace();    
  24.     }    
  25.     try {    
  26.         dos.close();    
  27.         dis.close();    
  28.     } catch (IOException e) {    
  29.         e.printStackTrace();    
  30.     }    
  31. }    

0 0