所以我正在解析已知的字节数。然而,前两个字节代表某个数字,然后下一个字节表示一个只有一个字节的数字,但可能接下来的四个字节都代表一个大的数字。有比我更好的方法来解析数据吗?
switch (i) {
//Status
case 2:
temp[3] = bytes[i];
break;
case 3:
temp[2] = bytes[i];
ret.put("Status", byteArrayToInt(temp).toString());
break;
//Voltage
case 4:
temp[3] = bytes[i];
break;
case 5:
temp[2] = bytes[i];
ret.put("Voltage", byteArrayToInt(temp).toString());
break;
//Lowest Device Signal
case 6:
temp[3] = bytes[i];
break;
case 7:
temp[2] = bytes[i];
ret.put("Lowest Device Signal", byteArrayToInt(temp).toString());
clearBytes(temp);
break;}
我正在循环遍历字节数组,并且我有一个开关,它知道哪些字节到哪个位置,例如,我知道第二个和第三个字节进入状态代码。所以我把它们组合成一个整数。temp字节数组是一个byte[] temp =新byte4。有什么更好的方法吗?
发布于 2013-08-01 19:38:04
ByteBuffer可以处理这件事。
byte[] somebytes = { 1, 5, 5, 0, 1, 0, 5 };
ByteBuffer bb = ByteBuffer.wrap(somebytes);
int first = bb.getShort(); //pull off a 16 bit short (1, 5)
int second = bb.get(); //pull off the next byte (5)
int third = bb.getInt(); //pull off the next 32 bit int (0, 1, 0, 5)
System.out.println(first + " " + second + " " + third);
Output
261 5 65541还可以使用get(byte[] dst, int offset, int length)方法获取任意数量的字节,然后将字节数组转换为所需的任何数据类型。
发布于 2013-08-01 19:35:16
您可以使用DataInputStream将多个字节读入ints或shorts。看起来一次只使用两个字节,所以您应该读取简短的内容而不是It (在Java中总是4个字节)。
但是在下面的代码示例中,我将使用您的描述“然而,前两个字节表示某个数字,然后下一个字节表示一个只有一个字节的数字,但接下来的四个字节可能代表一个数字”。
DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
//the first two bytes represent some number
ret.put("first", Short.toString(in.readShort()));
//next one represents a number that's only one byte
ret.put("second", Byte.toString(in.readByte()));
//next four all represent one number
ret.put("Lowest Device Signal", Integer.toString(in.readInt()));https://stackoverflow.com/questions/18002851
复制相似问题