1

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.

vica
  • 101
  • 1
  • 1
  • 8

1 Answers1

3

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    or simply an OutputStream – Scary Wombat Jul 09 '14 at 05:34
  • Thanks, interesting approach! I'll give it a go and accept answer if it works :) – vica Jul 09 '14 at 05:36
  • This answer is wrong. The [write(int)](http://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html#write-int-) method of ByteArray *does not* write an int as four bytes; it writes only the lowest 8 bits of the int. The above code will create a byte array containing only 4 bytes total! – VGR Jul 11 '14 at 00:53
  • @VGR Edited to use a DataOutputStream and writeInt. Which do write four bytes. – Elliott Frisch Jul 11 '14 at 00:59
  • Looking at the RFC linked in the question, I see that the terminal mode opcodes are not actually uint32s, but single bytes; it is their arguments which are uint32s. So I'm pretty sure the loop should contain a `writeByte` call followed by a `writeInt` call. From the RFC: "The stream consists of opcode-argument pairs wherein the opcode is a byte value. Opcodes 1 to 159 have a single uint32 argument." – VGR Jul 11 '14 at 01:03
  • @VGR It does say *The stream consists of opcode- argument pairs wherein the opcode is a byte value. Opcodes 1 to 159 have a single uint32 argument.* So I edited it to do that. – Elliott Frisch Jul 11 '14 at 01:10