0
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?

user1468729
  • 71
  • 1
  • 1
  • 3

1 Answers1

0

Try this:

int Header = 123456
ByteBuffer bytes = ByteBuffer.allocate(4);
bytes.putInt(Header);
byte[] buffer = bytes.array();

Byte array buffer contains integer value in 4 bytes.
Change to:

message[i] = bytes[i] & 0xFF;
Florent
  • 12,310
  • 10
  • 49
  • 58
Riskhan
  • 4,434
  • 12
  • 50
  • 76
  • try message[i] = bytes[i] & 0xFF; – Riskhan Sep 18 '12 at 09:33
  • Now tried that, too. It didn't help either. Btw, it required a cast to byte: message[i] = (byte) (bytes[i] & 0xFF); – user1468729 Sep 18 '12 at 09:46
  • Ok, I got this to work. It was sending the right thing but the toBinaryString and debug methods just printed it wrong probably because of a cast to int. I had to add the '0xff' thing to the receiving end and it started to work. Thank you anyway! I'd thumbs-up you if I could. – user1468729 Sep 18 '12 at 10:28