简体   繁体   English

实现二进制协议Java

[英]Implementing binary protocol Java

I am trying to implement a binary protocol in a Java Android application. 我正在尝试在Java Android应用程序中实现二进制协议。 The variables in this protocol are unsigned and are either uint32, uint16 or uint8. 该协议中的变量是无符号的,可以是uint32,uint16或uint8。

I am having trouble with sending integer values. 我在发送整数值时遇到麻烦。 For example, when I try to send a short with a value of 1, the server (written in C++) receives a value of 256. 例如,当我尝试发送值为1的短裤时,服务器(用C ++编写)收到的值为256。

After searching a bit, I saw some posts talking about endianess and all but it doesn't really give me an answer. 经过一番搜索之后,我看到一些帖子谈到了耐力症,所有这些都没有给我任何答案。

How can I manage to get the bits stored in my variables in Java aligned in the same fashion as the one in C++. 我如何设法以与C ++中相同的方式对齐存储在Java中的变量中的位。

Thanks 谢谢

C++ does not define the order in which bytes in multibyte integers are stored. C ++没有定义多字节整数中字节的存储顺序。 You should pick one standard and make sure that everyone uses it. 您应该选择一个标准,并确保每个人都使用它。

The standard API in Java has many classes that use big-endian byte order, so you might as well use that as the standard. Java中的标准API有许多使用big-endian字节顺序的类,因此您最好将其用作标准。 To receive these correctly in C++ you can use the ntohl and ntohs functions for the conversion, for example. 为了在C ++中正确接收这些内容,您可以使用ntohlntohs函数进行转换。

I solved it! 我解决了! It was a problem of endianess. 这是一个忍耐问题。 I solved it using the order() method of ByteBuffer. 我使用ByteBuffer的order()方法解决了它。

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

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