pimmling
pimmling

Reputation: 493

Java Programming: Integer value to Hexadecimal

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

Upvotes: 0

Views: 548

Answers (1)

JohnKlehm
JohnKlehm

Reputation: 2398

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);

Upvotes: 3

Related Questions