我在尝试创建网络字节标头时遇到了一些麻烦。头应该是 2 个字节长,它简单地定义了以下命令的长度。例如; 以下命令字符串"HED>0123456789ABCDEF"长度为 20 个字符,0014作为十六进制有符号的 2 补码,为该命令创建网络字节头,因为该命令少于 124 个字符。以下代码片段主要计算字节标头,并\u00000\u0014在命令少于 124 个字符时向命令添加以下前缀。但是,对于 124 个字符或以上的命令,if块中的代码不起作用。因此,我研究了可能的替代方案,并尝试了一些关于生成十六进制字符并将它们设置为网络字节标头的方法,但由于它们不是字节,因此无法正常工作(如else块中所示)。相反,else块只是返回0090一个153字符长的命令,这在技术上是正确的,但我不能像if块长度标头一样使用这个“长度”标头public static void main(String[] args) { final String commandHeader = "HED>"; final String command = "0123456789ABCDEF"; short commandLength = (short) (commandHeader.length() + command.length()); char[] array; if( commandLength < 124 ) { final ByteBuffer bb = ByteBuffer.allocate(2).putShort(commandLength); array = new String( bb.array() ).toCharArray(); } else { final ByteBuffer bb = ByteBuffer.allocate(2).putShort(commandLength); array = convertToHex(bb.array()); } final String command = new String(array) + commandHeader + command; System.out.println( command );}private static char[] convertToHex(byte[] data) { final StringBuilder buf = new StringBuilder(); for (byte b : data) { int halfByte = (b >>> 4) & 0x0F; int twoHalves = 0; do { if ((0 <= halfByte) && (halfByte <= 9)) buf.append((char) ( '0' + halfByte)); halfByte = b & 0x0F; } while (twoHalves++ < 1); } return buf.toString().toCharArray();}此外,通过执行以下三行,我已经设法在 Python 2 中实现了这一点!这将返回以下 153 个字符命令的网络字节头作为\x00\x99msg_length = len(str_header + str_command)command_length = pack('>h', msg_length)command = command_length + str_header + str_command也可以通过运行 Python 2 并输入以下命令来简单地复制:In [1]: import structIn [2]: struct.pack('>h', 153)Out[2]: '\x00\x99'任何可以解决此问题的帮助或线索将不胜感激。
添加回答
举报
0/150
提交
取消