Java编程:十六进制的整数值

时间:2011-05-01 21:12:07

标签: java

我有一个整数,我想将其转换为十六进制值。我正在构建一个消息头,下面是这个数组的每个字节值,表示有关消息的特定信息。

我想在下面的2个字节len1和len2中表示消息的长度。

我该怎么做?

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

由于

1 个答案:

答案 0 :(得分: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);