I am trying to convert an int to a byte[] and back again, but I think I am doing something wrong along the way. My code is basically:
byte[] array = new byte[4];
array[3] = (byte) ( num & 0xFF);
array[2] = (byte) ((num >> 8) & 0xFF);
array[1] = (byte) ((num >> 16) & 0xFF);
array[0] = (byte) ((num >> 24) & 0xFF);
And:
for (int i =0; i < 4; i++) {
num = (num << 8) + (array[i] & 0xff);
}
If I start off with the number 72, for example, after converting it to a byte array and back I get the number 795108710. Am I missing a step, or are maybe my endians mixed up? Thanks for your time.
Use a
ByteBuffer; it contains methods to encode many different data types without the need to worry about endian and the like: