Jignesh Ansodariya Jignesh Ansodariya - 3 months ago 19
Java Question

how to convert long to byte array in java?

I have made

long
value from byte array using this code

byte[] by = {07, 53 -70, 74};

long value = 0;

for (int i = 0; i < by.length; i++) {
value = ((value << 8) + (by[i] & 0xff));
}

System.out.println(value);


out put is
520010


now I want reverse process on this and I tried it this way

long ts = 520010;

tm_stp[0] = (byte) ((byte) ts>>24);
tm_stp[1] = (byte) ((byte) ts>>16);
tm_stp[2] = (byte) ((byte) ts>>8);
tm_stp[3] = (byte) ts;
for (byte b : tm_stp) {
System.out.println(b);
}


and output is
0 0 0 74


what is wrong in my second part of code please help me, Thanks!

Answer

The problem is the fact that you cast to byte too early:

tm_stp[0] = (byte) ((byte) ts>>24);
tm_stp[1] = (byte) ((byte) ts>>16);
tm_stp[2] = (byte) ((byte) ts>>8);
                   //^^^^

This causes the ts value to be truncated, replacing the first 24 bytes with 0s. After that, shifting by anything greater than or equal to 8 will return 0. To avoid incorrect behaviour with negative values, you should also use a bitmask. The correct code should look like this:

tm_stp[0] = (byte) ((ts >> 24) & 0xFF);
tm_stp[1] = (byte) ((ts >> 16) & 0xFF);
tm_stp[2] = (byte) ((ts >>  8) & 0xFF);
tm_stp[3] = (byte) ((ts >>  0) & 0xFF); // >> 0 not actually required, only for symmetry