3

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:

  1. 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.
  2. 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.

Matt Lick
  • 31
  • 2

3 Answers3

1

Nothing hard about any of those operations. DataInputStream and DataOutputStream take care of the stream->int->stream conversions, and ByteArrayInputStream and ByteArrayOutputStream take care of the stream->byte[]->stream conversions.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

There are two options:

  • the above mentioned bytebuffer
  • converting via bitshift:

    //int to byte[]
    int val = someval;
    byte[] bytes = new byte[4];
    
    for(int i = 0 ; i < 4 ; i++)
        bytes[i] = (byte) (val >>> (i * 8));
    
    //byte[] to int
    int val = 0;
    byte[] bytes = input();
    
    for(int i = 0 ; i < 4 ; i++)
        val |= ((int)(bytes[i])) << i * 8;
    
0

If you are defining your own format of the datagram, it's easy enough to establish that the nth 4 bytes of content represent an integer.

You then can use some simple conversion functions to go from int to byte[] and vice-versa.

A small class implementing this two methods should do:

public static byte[] toByteArray(int value) {
    byte[] b = new byte[4];

    // MSB to LSB
    b[0] = (byte) (value >> 24);
    b[1] = (byte) (value >> 16);
    b[2] = (byte) (value >> 8);
    b[3] = (byte) (value);

    return b;
}

public static int fromByteArray(byte[] value) {
    int i = ((((int) value[0]) & 0xFF) << 24) |
            ((((int) value[1]) & 0xFF) << 16) |
            ((((int) value[2]) & 0xFF) << 8) |
            ((((int) value[3] & 0xFF)));
    return i;
}
Vincenzo Pii
  • 18,961
  • 8
  • 39
  • 49