1

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!

Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113

2 Answers2

2

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
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
  • doing this `tm_stp[3] = (byte) ts; tm_stp[2] = (byte) (ts >> 8); tm_stp[1] = (byte) (ts >> 16); tm_stp[0] = (byte) (ts >> 24);` output is `0 7 -17 74` not actual – Jignesh Ansodariya Aug 10 '16 at 09:19
1

Don't convert ts to byte before shifting.

tm_stp[0] = (byte) (ts >> 24);
tm_stp[1] = (byte) (ts >> 16);
tm_stp[2] = (byte) (ts >> 8);
tm_stp[3] = (byte) ts;
Spotted
  • 4,021
  • 17
  • 33