2016-10-27 40 views
0

おはようネットワークバイトオーダー - テレグラム

私はATSソフトウェア経由でVerifone vx820ペダルと通信する必要があるアプリケーションを作成しています。そのドキュメントで

は、データを送信するために、それは述べて:

// 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(); 
      } 

私はしかし:

transmitting data

ここにある私は、それを行う方法でC#での例を持っていますこれはjavaです。 Javaへの変換に誰も助けてくれますか?これを行うためのJavaの簡単なメソッドはありますか?

は(山車、ダブルス、整数)私は

Javaでは
+0

'DataOutputStream'のプリミティブ書き込みメソッドはすべてビッグエンディアンです。 – EJP

答えて

1

、あなたが/エンコード、デコード、通常の値ができます素晴らしいByteBufferクラスを持って知っておくべき便利なものがあり、誰でもJavaのでATSを使用するアプリケーションを構築していますバイトの入れ替えByteBufferでは、使用しているエンディアンをorder(ByteOrder)メソッドで指定できます。

したがって、例のように、32ビットのビッグエンディアンで長さを付加したいと考えているのは、byte[] dataです。あなたは書きたい:

// 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がプレフィックス長であなたのデータを送信する)を持っていた場合、コードは非常に似ていますが、getInt、代わりにgetとなります。

+0

@ jmendeth今朝これを実行しようとしましたが、まだ動作していません。私がそれをデバッグすると、dataToSend配列を見ることができ、最初の4バイトは0、0、1、-43と読み取られます。ドキュメントでは、16進値を割り当てているように見えます。たとえば、469バイトのメッセージは1d5の16進数を持ちます。最初の4文字を00,00、01、d5に割り当てる必要があります。 何かが見つからない –

+0

いいえ、すべて正しいです。あなたは00、00、01、D5を期待します。 10進数では0、0、1、213です。しかし、バイトはJavaでは*符号付き*であるため、バイト213は-43で表されます(213が符号付きで-43に変換されます)。 –

+0

@ JamesKing Resuming:コードはあなたが言ったバイトを生成します。 –

関連する問題