0

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.

sasieightynine
  • 434
  • 1
  • 5
  • 16

2 Answers2

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