Well the questions is pretty much as the title. In my application I am sending array with 2 bytes using UDP packets. I want to know if there is a way to convert the integers from 0 to 2000 into bytes array of size two and after that to convert that byte array back to integer?
Asked
Active
Viewed 345 times
0
-
possible duplicates: http://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java http://stackoverflow.com/questions/6374915/java-convert-int-to-byte-array-of-4-bytes – Mark Mar 25 '13 at 02:41
-
http://stackoverflow.com/questions/2183240/java-integer-to-byte-array – Jeroen Vannevel Mar 25 '13 at 02:42
-
Look here; http://stackoverflow.com/questions/2183240/java-integer-to-byte-array – nommyravian Mar 25 '13 at 02:43
-
well these solutions are mainly for 4 bits integer ... my problem is actually how to represent the integers from 0 to 127 as 2 bytes ? – Andrey Mar 25 '13 at 02:45
-
Do the same thing with a short? http://docs.oracle.com/javase/1.5.0/docs/api/java/nio/ByteBuffer.html#putShort(short) – James Mar 25 '13 at 02:51
-
a short is two bytes, use those – sjr Mar 25 '13 at 03:43
1 Answers
0
You can use java.nio ByteBuffer conversions
to bytes
int[] ia = { 1, 2, 3 };
ByteBuffer bb = ByteBuffer.allocate(ia.length * 4);
for (int i : ia) {
bb.putShort((short)i);
}
byte[] ba = bb.array();
to ints
ShortBuffer sb = ByteBuffer.wrap(ba).asShortBuffer();
int[] ia = new int[sb.limit() / 2];
for(int i = 0; i < ia.length; i++) {
ia[i] = sb.get();
}

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275