java中int与byte的相互转换

我们都知道,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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值