java中int与byte〔4〕的相互转换

 我们都知道,JAVA中的基本数据类型有int,byte,char,long,float,double...,它们与引用数据类型很不一样,之所有在如此面向对象的JAVA语言中依然支持这些值类型,就是考虑到性能的原因。现在,同样是因为考虑到性能,我们需要一种高效的方法使int与byte[]能够自由的相互转换,理由就是,我们需要在网络上传送数据,而网络上的数据都是byte数据流,这就需要一个int-> byte[]与byte[] -> int的方法。
  简单的方法,我们可以用DataOutputStream与ByteArrayOutputStream来将int转换成byte[],方法就是:
int i = 0;
ByteArrayOutputStream boutput = newByteArrayOutputStream();
DataOutputStream doutput = newDataOutputStream(boutput);
doutput.writeInt(i);
byte[] buf = boutput.toByteArray();
 执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStream与ByteArrayInputStream。
byte[] buf = new byte[4];
ByteArrayInputStream bintput = newByteArrayInputStream(buf);
DataInputStream dintput = new DataInputStream();
int i = dintput.readInt();
  上面的方法可以达到int<->byte[]的转化,下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。
  int -> byte[]

privatebyte[] intToByteArray(final int integer) {
int byteNum = (40 -Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer))/ 8;
byte[] byteArray = new byte[4];

for (int n = 0; n < byteNum; n++)
byteArray[3 - n] = (byte) (integer>>> (n * 8));

return (byteArray);
}

  byte[] -> int

public static int byteArrayToInt(byte[] b, int offset) {
       int value= 0;
       for (int i = 0; i < 4; i++) {
           int shift= (4 - 1 - i) * 8;
           value +=(b[i + offset] & 0x000000FF) << shift;
       }
       return value;
 }
========================================

import java.io.*;

public class IOTest {
public static void main(String[] args) throws Exception {
  int i = 65535;  
  byte[] b = intToByteArray1(i);
  for(byte bb : b) {
   System.out.print(bb + " ");
  }
}

public static byte[] intToByteArray1(int i) {  
  byte[] result = new byte[4];  
  result[0] = (byte)((i >> 24) & 0xFF);
  result[1] = (byte)((i >> 16) & 0xFF);
  result[2] = (byte)((i >> 8) & 0xFF);
  result[3] = (byte)(i & 0xFF);
  return result;
}

public static byte[] intToByteArray2(int i) throws Exception {
  ByteArrayOutputStream buf = new ByteArrayOutputStream();  
  DataOutputStream out = new DataOutputStream(buf);  
  out.writeInt(i);  
  byte[] b = buf.toByteArray();
  out.close();
  buf.close();
  return b;
}

posted on 2011-11-17 20:02  Mayola  阅读(47343)  评论(2编辑  收藏  举报