0

In the following java code-snippet you'll see this line packetLengthMax += bytes.toByteArray()[43]; My question is: How does this work?

byte[] dataBuffer = new byte[265];
int packetLength = 0;
int packetLengthMax = 44;
ByteArrayOutputStream   bytes       = new ByteArrayOutputStream();
DataOutputStream        outMessage  = new DataOutputStream(bytes);
/* Client = Socket*/
DataInputStream         clientIn    = new DataInputStream(Client.getInputStream());
while (packetLength < packetLengthMax) {
    packetLength += clientIn.read(dataBuffer);
    outMessage.write(dataBuffer);           
    if (packetLength >= 43) {
        packetLengthMax += bytes.toByteArray()[43];
    }
}

My explanation: First a socket (Client) is passed to the code. Then it does the setup of all variables. In the while loop, it reads all data that comes from the socket. Then it also writes this data to the DataOutputStream. But in the if statement - it adds a byte array to an integer.
How does it work? I don't get that point. Thank you for helping!

Peter
  • 394
  • 7
  • 20

1 Answers1

1

It's not adding the whole byte array, it's just adding the byte at position 43. (i.e. the 44th byte in the array).

Nicholas Daley-Okoye
  • 2,267
  • 1
  • 18
  • 12
  • Ok, I undestand that and it is the correct answer on my question. But how does that work? Adding a byte to an integer? – Peter Feb 27 '15 at 09:23
  • 1
    The only difference between byte and integer is that a byte is one byte long (-128 to 127), and an int is 4 bytes long (-2,147,483,648 to 2,147,483,647). The byte gets converted into an integer and then they are added. – Nicholas Daley-Okoye Feb 27 '15 at 11:56