javatypesendianness

Convert a byte array to integer in Java and vice versa


I want to store some data into byte arrays in Java. Basically just numbers which can take up to 2 Bytes per number.

I'd like to know how I can convert an integer into a 2 byte long byte array and vice versa. I found a lot of solutions googling but most of them don't explain what happens in the code. There's a lot of shifting stuff I don't really understand so I would appreciate a basic explanation.


Solution

  • Use the classes found in the java.nio namespace, in particular, the ByteBuffer. It can do all the work for you.

    byte[] arr = { 0x00, 0x01 };
    ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
    short num = wrapped.getShort(); // 1
    
    ByteBuffer dbuf = ByteBuffer.allocate(2);
    dbuf.putShort(num);
    byte[] bytes = dbuf.array(); // { 0, 1 }