【问题标题】:Network byte order - telegram网络字节序 - 电报
【发布时间】:2016-10-27 18:23:10
【问题描述】:

早安

我正在编写一个需要通过 ATS 软件与 Verifone vx820 ped 通信的应用程序。

在他们的文档中,为了传输数据,它指出:

我在 c# 中有一个示例说明如何做到这一点,这里是:

// Format of ATS telegram:
            //
            //       +---------------------------- ... ---------------------------------+
            //       | xx | xx | xx | xx | Data                                         |
            //       +---------------------------- ... ---------------------------------+
            // Byte  |  0 |  1 |  2 |  3 | 4       ... 
            //       |                   |
            // Field | -- Data Length -- | Data
            //
            // Data length is 4 bytes; network byte order (big-endian)

            try
            {
                // Attempt to make TCP connection to ATS
                Connect();

                // Convert data length to network byte order...
                int iLengthNetworkByteOrder = IPAddress.HostToNetworkOrder(Data.Length);

                // ...then convert it to a byte array
                byte[] DataLength = BitConverter.GetBytes(iLengthNetworkByteOrder);

                // Construct the send buffer, prefixing the data with the data length as shown above
                m_SendBuffer = new byte[DataLength.Length + Data.Length];
                DataLength.CopyTo(m_SendBuffer, 0);
                Data.CopyTo(m_SendBuffer, DataLength.Length);

                // Signal the background thread there is data to send
                m_eventSendDataAvailable.Set();
            }

但是我正在构建它是 java。任何人都可以帮助我转换为 Java。 Java 中有没有简单的方法可以做到这一点?

有没有人用java构建了一个使用ATS的应用程序,有什么有用的我应该知道的

【问题讨论】:

  • DataOutputStream的原始写法都是大端的。

标签: java networking


【解决方案1】:

在 Java 中,您拥有出色的 ByteBuffer 类,可让您将普通值(整数、浮点数、双精度数)编码/解码为字节/字节。 ByteBuffer 允许您通过其order(ByteOrder) 方法指定使用的字节序。

所以,假设您有一个byte[] data,您想在前面加上一个 32 位大端的长度,如您的示例所示。你会写:

// Create a buffer where we'll put the data to send
ByteBuffer sendBuffer = ByteBuffer.allocate(4 + data.length);
sendBuffer.order(ByteOrder.BIG_ENDIAN); // it's the default, but included for clarity

// Put the 4-byte length, then the data itself
sendBuffer.putInt(data.length);
sendBuffer.put(data);

// Extract the actual bytes from our sendBuffer
byte[] dataToSend = sendBuffer.array();

如果您遇到相反的情况(ATS 向您发送带有前缀长度的数据),代码将非常相似,但使用 getIntget 代替。

【讨论】:

  • @jmendeth 今天早上尝试运行,但它仍然无法正常工作。当我调试它时,我可以看到 dataToSend 数组,前 4 个字节读取为 0、0、1、-43。在文档中,看起来他们正在分配十六进制值,例如,一条 469 字节的消息将具有 1d5 的十六进制,我需要将前 4 个字符分配给 00、00、01、d5。我错过了什么
  • 不,都是正确的。您期望 00、00、01、D5。在十进制中,它是 0, 0, 1, 213。但是,字节在 Java 中是 有符号 数字,因此字节 213 由 -43 表示(转换为有符号的 213 是 -43)。跨度>
  • @JamesKing Resuming:代码产生你说的字节。
猜你喜欢
  • 2022-01-22
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多