从字节数组中提取字节在指定位置

时间:2013-11-20 16:50:17

标签: java android arrays data-structures

你好,我是java中字节操作的新手。我已经有流式格式的字节数组

1-> datapacketlength (length of name) (first byte)
2-> name  (second byte + datapacket length)
3-> datapacketlength (length of datetime)
4-> current date and time

如何提取姓名和当前日期和时间。should i use Arrays.copyOfRange() method.

来自

MCD

3 个答案:

答案 0 :(得分:2)

您可以使用ByteBuffer并使用当前的字节数组,然后使用它附带的方法来获取下一个float,int等(例如buffer.getIntbuffer.getFloat)。

使用我认为的wrap方法创建新的bytebuffer时,可以获取字节数组的一部分。可能性是无止境 :)。要按照要求获得字符串,您只需要执行以下操作:

 byte[] name = new byte[nameLength];
 buffer.get(name);
 nameString = byteRangeToString(name);

其中byteRangeToString是一个返回传递的byte []数据的新字符串表示的方法。

public String byteRangeToString(byte[] data)
{
    try
    {
         return new String(data, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
         /* handle accordingly */
    }
}

请参阅:http://developer.android.com/reference/java/nio/ByteBuffer.html

如果过度使用,使用copyOfRange()可能会导致内存问题。

答案 1 :(得分:0)

如下:

int nameLength = 0;
int dateLength = 0;
byte[] nameByteArray;
byte[] dateByteArray

for(int i=0; i<bytesArray.length; i++){
    if(i == 0){
        nameLength = bytesArray[i] & 0xFF;
        nameByteArray = new byte[nameLength];
    }
    else if(i == nameLength+1){
        dateLength = byteArray[i] & 0xFF;
        dateByteArray = new byte[dateLength];
    }
    else if(i < nameLength+1){
        nameByteArray[i-1] = bytesArray[i];
    }
    else{
        dateByteArray[i-(nameLength+1)] = bytesArray[i];
    }
}

答案 2 :(得分:0)

您想使用DataInputStream

相关问题