vica
vica

Reputation: 101

Encoding Uint32 ints into Java byte array

I'm using a third party ssh library and I need to specify some options as a byte array. Namely the terminal modes (http://www.ietf.org/rfc/rfc4254.txt).

My problem is that I need to create a byte array that is the 'equivalent' of a uint array {128, 36000, 129, 36000} and I am not quite sure on how to achieve that. By equivalent I mean - I don't care what number it represents in java, I do care that the correct bytes are sent down the socket.

Any hints? Thanks in advance.

Upvotes: 1

Views: 377

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

If I understand your question, then I believe you can do it with a ByteArrayOutputStream wrapped by a DataOutputStream and something like this,

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
int[] ints = new int[] { 128, 36000, 129, 36000 };
try {
  for (int i = 0; i < ints.length; i += 2) {
    dos.writeByte(ints[i]);
    dos.writeInt(ints[1 + i]);
  }
  dos.close();
} catch (IOException e) {
  e.printStackTrace();
}
byte[] bytes = baos.toByteArray();

Or, use the client's OutputStream directly.

Upvotes: 3

Related Questions