How to send a Java integer in four bytes to another application?

Posted by user1468729 on Stack Overflow See other posts from Stack Overflow or by user1468729
Published on 2012-09-18T09:24:48Z Indexed on 2012/09/18 9:37 UTC
Read the original article Hit count: 179

Filed under:
|
|
public void routeMessage(byte[] data, int mode) {
    logger.debug(mode);
    logger.debug(Integer.toBinaryString(mode));
    byte[] message = new byte[8];
    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
    DataOutputStream doStream = new DataOutputStream(baoStream);
    try {
        doStream.writeInt(mode);
    } catch (IOException e) {
        logger.debug("Error converting mode from integer to bytes.", e);
        return;
    }
    byte [] bytes = baoStream.toByteArray();
    bytes[0] = (byte)((mode >>> 24) & 0x000000ff);
    bytes[1] = (byte)((mode >>> 16) & 0x000000ff);
    bytes[2] = (byte)((mode >>> 8) & 0x00000ff);
    bytes[3] = (byte)(mode & 0x000000ff);
    //bytes = byteBuffer.array();
    for (byte b : bytes) {
        logger.debug(b);
    }
    for (int i = 0; i < 4; i++) {
        //byte tmp = (byte)(mode >> (32 - ((i + 1) * 8)));
        message[i] = bytes[i];
        logger.debug("mode, " + i + ": " + Integer.toBinaryString(message[i]));
        message[i + 4] = data[i];
    }
    broker.routeMessage(message);
}

I've tried different ways (as you can see from the commented code) to convert the mode to four bytes to send it via a socket to another application. It works well with integers up to 127 and then again with integers over 256. I believe it has something to do with Java types being signed but don't seem to get it to work. Here are some examples of what the program prints.

127
1111111
0
0
0
127
mode, 0: 0
mode, 1: 0
mode, 2: 0
mode, 3: 1111111

128
10000000
0
0
0
-128
mode, 0: 0
mode, 1: 0
mode, 2: 0
mode, 3: 11111111111111111111111110000000

    211
    11010011
    0
    0
    0
    -45
    mode, 0: 0
    mode, 1: 0
    mode, 2: 0
    mode, 3: 11111111111111111111111111010011

306
100110010
0
0
1
50
mode, 0: 0
mode, 1: 0
mode, 2: 1
mode, 3: 110010

How is it suddenly possible for a byte to store 32 bits? How could I fix this?

© Stack Overflow or respective owner

Related posts about integer

Related posts about bytearray