将十六进制字节数组转换为int

时间:2018-11-10 21:26:58

标签: java

我从客户端将输入流中的4个十六进制字节读取到服务器端的数组中,例如\ x00 \ x00 \ x02 \ x24(十六进制为224)。我需要将其转换为int。怎么办呢?

1 个答案:

答案 0 :(得分:1)

平移并求和(就像在DataInputStream#readInt()中所做的那样)

byte[] bytes = {0, 0, 0x2, 0x24};
int i = ((bytes[0] << 24) + (bytes[1]<< 16) + (bytes[2]<< 8) + (bytes[3] << 0));
System.out.println(i);

输出:

548

也许您正在寻找DataInputStream

byte[] bytes = {0, 0, 0x2, 0x24};
DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(bytes));
System.out.println(inputStream.readInt());

输出:

548