1

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

2
  • How long are the length fields? Is this received from a socket or locally read from a file? Commented Nov 20, 2013 at 16:58
  • length field contain one byte and it Would varying. Commented Nov 20, 2013 at 17:02

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

You want to use a DataInputStream.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.