Java编程: Integer value to Hexadecimal

标签 java

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

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

相关文章:

javascript - MultipartFile 数组未发送到 spring Controller

java - Java中的所有通配符都可以用非通配符类型代替吗?

java - 在 Java 中加载 OpenGL 和 LWJGL3 中的纹理

java - Drools/Kie-Server/Busines-Central 7.28.0 当 kie-server 访问业务中心上的 websocket Controller 时收到 403

java - 如何从此对象中访问 deviceName 和 deviceHardwareAddress?

java - 在我的动态 Web 项目中运行 Tomcat 服务器时出错

java - 将 visualvm 连接到 websphere 7

java - 从不同类中的线程调用时不会发生重绘

java - 从 Java 中的不同类追加到私有(private) TextArea

java - 当没有调用 'matching' 方法时,Matcher 抛出 IllegalStateException 的理由