0

I'm trying to create an array of 16-bit values to send over a socket in network order.

First, I have defined an array to hold the value:

char[] txbuf = new char[32]; // Java "char" is 16-bits

Next, I open the socket and create the OutputStreamWriter:

InetAddress serverAddr = InetAddress.getByName(host);
socket = new Socket(serverAddr, port);
writer = new OutputStreamWriter(socket.getOutputStream(),Charset.forName("UTF-16BE"));

Then I initialize the data to send:

txbuf[0] = 0x1234;
...
txbuf[31] = 0xFFFF;

Finally, I send the data to the socket:

writer.write(txbuf,0,32);
write.flush();

However, the device I am sending the data to is behaving erratically, and I suspect there is some issue with the UTF-16BE conversion actually doing something to the data (filtering characters out?) besides the simple network order translation. Everything works fine in C, but not in the Java port.

I have seen various convoluted schemes for trying to write raw binary data but was trying for what seemed like the simplest and most straightforward method.

Is there a problem with the above scheme?

5
  • Are any of the characters you are writing surrogates? Have you looked at the actual data that is being sent? Commented Sep 23, 2014 at 22:57
  • @DavidConrad The data can be any random binary values. Commented Sep 23, 2014 at 23:04
  • @DavidConrad If I understand what you are saying, if any of the values are in the surrogate range (0xD800..0xDBFF / 0xDC00..0xDFFF) then some translation is going to occur? Commented Sep 23, 2014 at 23:08
  • I'm not sure, actually, but I think it's worth investigating. Commented Sep 23, 2014 at 23:08
  • Does the device really understand UTF-16BE? If not, you should be writing bytes, not chars. Don't use chars as though they are 16 bits on the wire. Commented Sep 23, 2014 at 23:54

1 Answer 1

3

If you want to write bytes, instead of characters, you should be using the raw OutputStream instead of a Writer. OutputStream deals with bytes, Writer deals with characters, and a charset converts between them.

DataOutputStream writes primitive values to an OutputStream in big-endian order without any byte order marks or other charset issues.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.