您的位置:首页 > 编程语言 > Java开发

java中int与byte的相互转换

2013-03-19 14:39 483 查看
我们都知道,J***A中的基本数据类型有int,byte,char,long,float,double...,它们与引用数据类型很不一样,之所有在如此面向对象的J***A语言中依然支持这些值类型,就是考虑到性能的原因。现在,同样是因为考虑到性能,我们需要一种高效的方法使int与byte[]能够自由的相互转换,理由就是,我们需要在网络上传送数据,而网络上的数据都是byte数据流,这就需要一个int-> byte[]与byte[] -> int的方法。

  简单的方法,我们可以用DataOutputStreamByteArrayOutputStream来将int转换成byte[],方法就是:
int i = 0;
ByteArrayOutputStream boutput = new ByteArrayOutputStream();
DataOutputStream doutput = new DataOutputStream(boutput);
doutput.writeInt(i);
byte[] buf = boutput.toByteArray();

执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStreamByteArrayInputStream

byte[] buf = new byte[4];
ByteArrayInputStream bintput = new ByteArrayInputStream(buf);
DataInputStream dintput = new DataInputStream();
int i = dintput.readInt();

下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。

注:numberOfLeadingZeros(int i) 在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前,返回零位的数量

//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;
 }
两种Int->byte[]的方法如下示例代码所示

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: