繁体   English   中英

Java 编程:Integer 值转十六进制

[英]Java Programming: Integer value to Hexadecimal

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

我想用下面的 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM