0

I have an integer and I want to convert it to hex value. I am building a message header with each byte value of this array below indicating a specific information about the message.

I want to represent the length of the message in 2 bytes len1 and len2 below.

How do I do this?

 byte[] headerMsg =new byte []  {   0x0A, 0x01, 0x00, 0x16,
                                                0x11, 0x0d, 0x0e  len1 len2};
 int lenMsg //in 2 bytes 

Thanks

3
  • 3
    This may be of help: stackoverflow.com/questions/185747/… Commented May 1, 2011 at 21:14
  • When you read the data, it is far more useful to have the length at the start, otherwise you need to know the length, to find the length, which isn't very useful. Commented May 1, 2011 at 22:13
  • You still need to have some idea of the byte layout before hand. Even if the length is at the start of the header you don't know how many bytes it is. Having a header with a static length like this initial array is, and reserving the last 2 bytes for length is just about the same as having the 2 bytes at the front. Commented May 1, 2011 at 22:36

1 Answer 1

3
byte[] headerMsg =new byte []  {
    0x0A, 0x01, 0x00, 0x16,
    0x11, 0x0d, 0x0e,
    0x00, 0x00 // to be filled with length bytes
};

int hlen = headerMsg.length;

// I assume the bodyMsg byte array is defined elsewhere
int lenMsg = hlen + bodyMsg.length;


// lobyte of length - mask just one byte with 0xFF
headerMsg[hlen - 1] = (byte) (lenMsg & 0xFF);

// hibyte of length - shift to the right by one byte and then mask
headerMsg[hlen - 2] = (byte) ((lenMsg >> 8) & 0xFF);
Sign up to request clarification or add additional context in comments.

3 Comments

The formatting was going screwy for me not sure what happened. Looks ok now though.
CoolBeans fixed that for you. For future answers, see: stackoverflow.com/editing-help
Thanks a lot. Just a little curiosity, I only wanted the length in the header of the message to indicate how much length is the "body of the message". Is it good practice to also add the header length along??

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.