1

I'm currently writing a small application that interacts with a Windows driver via a callback. This application records various XY coordinates and button states, which are expressed in integers. The application will send this this data to callback via a local network. My experience with packets is limited to say the least, but I at least know that I need to convert the values into a byte array.

For example, below are two sets of arrays:

int[][] axes = { {75, 150}, {0, 40} };

int[] buttons= {0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1}

How exactly would I go about converting these values into a byte array? Also, what use do offsets serve? I've looked around and I can't quite get my head around it.

Andy Res
  • 15,963
  • 5
  • 60
  • 96
tripleblep
  • 530
  • 7
  • 17
  • All the answers assume that you don't mind using 4 bits for every integer (even if it could be converted using one byte) . If you have a large array of low-valued integers, you might want to check out another solution using bit-coding on the highest-order bits but I don't have enough time to write it right now. If you still want to find out about it in the evening I'll post it. – nstosic Jan 14 '15 at 08:19
  • @NitroNbg I managed to figure it out. Thanks for the help, though! – tripleblep Jan 15 '15 at 11:38

2 Answers2

2

convert int to byte[]. create this function:

byte[] toBytes(int i)
{
  byte[] result = new byte[4];

  result[0] = (byte) (i >> 24);
  result[1] = (byte) (i >> 16);
  result[2] = (byte) (i >> 8);
  result[3] = (byte) (i /*>> 0*/);

  return result;
}

Run in a loop on your int[], for each cell call to the function and add result to an array of bytes.

Miki Franko
  • 687
  • 3
  • 7
1

You need to loop through all the elements of the array and then extract the bytes one by one of each integer. Assuming an integer is 4 bytes, you could use bit shifting operations and extract each 8 bits from the integer. After that, using the byte data type you can create arrays.

e.g. a = 10110011 11101010 11110101 11010100 //in binary

      byte 3    byte 2  byte 1  byte 0

byte 0 = a & 0xFF

byte 1 = (a >> 8) & 0xFF

byte 2 = (a >> 16) & 0xFF

byte 3 = (a >> 24) & 0xFF

To convert back to integer, for each set of 4 bytes in the bytes array:

number = (byte3 << 24) | (byte2 << 16) | (byte 1 << 8) | byte0

  • 1
    True and for recompiling it back to integer would be `int originalInt = byte0 | (byte1 << 8) | (byte2 << 16) | (byte3 << 24)` – nstosic Jan 14 '15 at 08:15