I am trying to program a handshake type message as follows where C=Client S=Server:
C-->S: "I'd like to talk" //session initiation
S-->C: "80" //(n, randomly generated number)
C-->S: "81" //(n+1)
S: "does n= (n+1)-1?" //confirms the connection.
For the purposes of this question assume that the logic above is correct. I would like the random number I generated to be a 32 bit number (i.e. 4 bytes sent in a UDP datagram). Since an int is 32 bits, I would prefer to use this data type, but I seem to run into one of two problems:
- When using an array of bytes, it is easy to send in a datagram but difficult to perform a simple math operation (such as subtract 1) for a 32 bit number.
- When using an int it is easy to perform a simple math operation, but it is difficult to convert between ints and bytes when sending back and forth between the client and server.
I found a method that can convert from an int to bytes. I found some information regarding using a Bytebuffer to convert to an int, but I'm not sure it's even correct. Is there an easier way to go about a process of sending an int in a datagram? It seems like an extraordinary amount of work to keep converting back and forth between bytes and ints.