Here i have one String and i converted this string to long and than this long value converted into bytes. This byte array length is 6.
final byte[] tagBytes = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)
.putLong(Long.parseLong("02201156116")).array();
System.arraycopy(tagBytes, 0, tag, 0, 6);
Log.d("TAG", "TAG in bytes "+Arrays.toString(tag));
Here i got output like this [52, 84, 49, -125, 0, 0]
Now i want to convert this output bytes in String as like before "02201156116"
So here i have to first order bytes in BIG_ENDIAN first and then wrap Bytes and get long value from it.
But Here i am Surprised why it is not work for
ByteBuffer.wrap(tempDateBytes).order(ByteOrder.BIG_ENDIAN).getLong()
this and its work for
ByteBuffer.wrap(tempDateBytes).order(ByteOrder.LITTLE_ENDIAN).getLong() this, By d way we have to Apply BIG_ENDIAN becuase when we convert long to bytes we used LITTLE_ENDIAN. So i think we have to use here BIG_ENDIAN. but its not works for BIG_ENDIAN, its works for LITTLE_ENDIAN.
This code i used to convert [52, 84, 49, -125, 0, 0] to 02201156116
long time,time1;
final byte[] tempDateBytes = new byte[8];
System.arraycopy(tagBytes, 0, tempDateBytes, 0, 6);
time1 = ByteBuffer.wrap(tempDateBytes).order(ByteOrder.BIG_ENDIAN).getLong();
time = ByteBuffer.wrap(tempDateBytes).order(ByteOrder.LITTLE_ENDIAN).getLong();
Log.d("TAG", "Orignal TAG "+time);
Log.d("TAG", "BAD TAG "+time1);
Think about it in terms of
short. Let’s say we encode the value 258:Now, if we put this in an array, we must decide which byte we put at index 0. We can do
or
No order is per se better than the other, but the crucial point is to remember which order we used, when we ever want do decode the array and want to get the value 258 back.
This is the purpose of LITTLE_ENDIAN and BIG_ENDIAN. On encoding, it tells the byte order to use. On decoding, it tells the byte order we used when we encoded.
Hence, to not mess things up, be sure to use the same byte order on encoding and decoding.