Integer numbers are stored in
two's-complement binary format. These numbers are grouped into blocks of 8 bits - bytes. In 32-bit systems, the size of a variable of type int is 32 bits, or 4 bytes.
A single byte in two's-complement can store numbers from -128 to 127. Adding additional bits expands the range. Any number that is less than -128 or greater than 127 cannot be stored in a single byte in two's-complement format. A 32-bit int, however, can store any number from –2,147,483,648 to 2,147,483,647.
As nmi said, your code will not work. By casting a number like, say, 4000 to a byte, you are forcing the compiler to ignore bits of the number that cannot be ignored. The result is that your number will come out as garbage.
In binary, specifically two's complement, 4000 is written 111110100000. We can break this up into bytes by selecting groups of four bits, starting at the right edge of the number:
00001111 | 10100000 Byte 1 Byte 2
Here you can see that it takes two bytes to represent 4000 in binary. You can play around with this yourself with the Windows calculator program by putting it in Scientific mode.
Your program already stores 4000 as a 32-bit int (4 bytes total). In order to make sure that all 4 bytes are kept in the byte array, your coworker's code is basically doing the same thing I did above: it splits the 4 bytes apart and stores them into the array. Because each element of the array is 1 byte, no single element can hold the whole 4-byte value.
If your compiler is worth anything, it will complain at you if you try to do this:
byte byte_array[10];int x = 5000;byte_array[0] = x;
It should warn you about loss of information or a similar type-conversion warning. Pay attention to these; ignoring them can lead to very bad bugs. Remember the golden rule of casts: if you see a type cast in code for integer numbers, you should immediately be suspicious of bad code. This is a royal P.I.T.A. in Java, because casting is required all over the place - but, of course, if you see Java, you should immediately be suspicious of bad code anyways [wink]