mcd
mcd

Reputation: 1432

Extract Bytes At specified location from byte array

hello i am new with byte manipulation in java. i already have byte array with flowing format

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

how can i extract the name and current date and time.should i use Arrays.copyOfRange() method.

Regards from

mcd

Upvotes: 1

Views: 5227

Answers (3)

Domi
Domi

Reputation: 24548

You want to use a DataInputStream.

Upvotes: 0

pfairbairn
pfairbairn

Reputation: 451

You can use ByteBuffer and use your current byte array, then use the methods that come with it to get the next float, int etc (such as buffer.getInt and buffer.getFloat).

You can get a portion of your byte array when you create a new bytebuffer by using the wrap method I believe. The possibilities are endless :). To get strings as you asked, you simply need to do something like:

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

where byteRangeToString is a method to return a new string representation of the byte[] data you pass it.

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

See: http://developer.android.com/reference/java/nio/ByteBuffer.html

Using copyOfRange() may run you into memory issues if used excessively.

Upvotes: 2

user2058839
user2058839

Reputation:

What about something like :

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];
    }
}

Upvotes: 0

Related Questions