我有一个整数,我想将其转换为十六进制值。我正在构建一个消息头,其中该数组的每个字节值指示有关该消息的特定信息。
我想用下面的 2 个字节 len1 和 len2 来表示消息的长度。
我该怎么做?
byte[] headerMsg =new byte [] { 0x0A, 0x01, 0x00, 0x16,
0x11, 0x0d, 0x0e len1 len2};
int lenMsg //in 2 bytes
谢谢
最佳答案
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);
关于Java编程: Integer value to Hexadecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5851450/