java 如何将byte[4]数组转换成一个int型数据

如题所述

java中将4字节的byte数组转成一个int值的工具方法如下:
/**
* @param byte[]
* @return int
*/
public static int byteArrayToInt(byte[] b){
byte[] a = new byte[4];
int i = a.length - 1,j = b.length - 1;
for (; i >= 0 ; i--,j--) {//从b的尾部(即int值的低位)开始copy数据
if(j >= 0)
a[i] = b[j];
else
a[i] = 0;//如果b.length不足4,则将高位补0
}
int v0 = (a[0] & 0xff) << 24;//&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位
int v1 = (a[1] & 0xff) << 16;
int v2 = (a[2] & 0xff) << 8;
int v3 = (a[3] & 0xff) ;
return v0 + v1 + v2 + v3;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-28

import java.math.BigInteger;

public class HexNumberToInteger {

public static void main(String[] args) {

byte[] x = { 127, -1, -1, -1 };

byte[] y = { -128, 0, 0, 0 };

BigInteger xx = new BigInteger(x);

System.out.println("整数最大值:" + xx.intValue());

BigInteger yy = new BigInteger(y);

System.out.println("整数最小值:" + yy.intValue());

}

}

第2个回答  2012-02-29
//如果你是想把byte[]数组变成int[]数组
public class Maintest{
public static void main(String[] args) {

byte[] bs=new byte[]{-1,2,4,5};
int[] is=new int[bs.length];

for(int i=0;i<bs.length;i++)
{
is[i]=(int)bs[i];
System.out.println(is[i]);
}

}
}

//如果你只是想把byte数据连成int数据
public class Maintest {
public static void main(String[] args) {

byte[] bs=new byte[]{-1,2,3,4};

StringBuffer sb=new StringBuffer();
for(byte b:bs)
{
sb=sb.append(b);
}

int num=Integer.parseInt(sb.toString());
System.out.println(num);

}
}
第3个回答  推荐于2017-11-25
看下这个是不是你想要的。
public class Test {
public static void main(String[] args) {
byte[] byteArray = new byte[] { 1, 2, 3, 4 };
StringBuilder sBuilder = new StringBuilder();
for (byte b : byteArray) {
sBuilder.append(b);
}
int intValue = Integer.valueOf(sBuilder.toString());
System.out.println(intValue);
}
}本回答被提问者和网友采纳
第4个回答  推荐于2018-02-27
byte[] bs = new byte[4];
bs[0] = 1;
bs[1] = 2;
bs[2] = 3;
bs[3] = 4;

int r = 0;
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
//连接管道
pis.connect(pos);
DataInputStream dis = new DataInputStream(pis);
DataOutputStream dos = new DataOutputStream(pos);
//先写4个字节
dos.write(bs,0,bs.length);
//读取整型
r = dis.readInt();

System.out.println(r);
dis.close();
dos.close();
相似回答