I have int
numbers with values between 0-65535. I need to store each number as a byte
array of 2 bytes length, whether the number could fit on 1 byte as well or not. Once the numbers are stored in byte arrays, I need to be able to convert them back to int
. Right now I don't know how to store a number that is not between -32,768 and 32,767 on 2 bytes and be able to properly convert it back to its original int
value.
Asked
Active
Viewed 419 times
0

sasieightynine
- 434
- 1
- 5
- 16
-
Possible duplicate of [Java - Convert int to Byte Array of 4 Bytes?](https://stackoverflow.com/questions/6374915/java-convert-int-to-byte-array-of-4-bytes) – Progman Nov 01 '19 at 14:07
-
I need 2 bytes, not 4. – sasieightynine Nov 01 '19 at 14:09
-
Look at using shift to access desired byte and AND to stripe off sign bits – NormR Nov 01 '19 at 14:11
2 Answers
1
You can store values from 0-65535
in a char
-value and convert a char
to byte[]
(with a length of 2) using the following method:
public static byte[] toBytes(char c) {
return ByteBuffer.allocate(Character.BYTES).putChar(c).array();
}
See here
EDIT:
Works backwards using ByteBuffer
to:
public static char charFromBytes(byte[] bytes) {
return ByteBuffer.wrap(bytes).getChar();
}

Felix
- 2,256
- 2
- 15
- 35
0
Storing the first byte as: (byte) (myIntNumber >> 8)
and the second as (byte) myIntNumber
seems working just fine for int -> byte array conversion, I'm still curious about how do I get back the int properly from a byte array.

sasieightynine
- 434
- 1
- 5
- 16
-
You can just use my solution and cast from `int` to `char` and vice-versa – Felix Nov 01 '19 at 21:21