J
jeffdeanda
I'm having trouble converting a byte array to long. The code below
results in a long value of 4096, which is way off. If I remove on or
the other values and replace it with 0 it still results in the same
outcome. I'm thinking there's a problem with the shifting in the 2nd to
last line, but am unable to figure it out. Any thoughts?
Here's the code:
short[] ss = new short[4];
ss[0] = 0;
ss[1] = 4096;
ss[2] = 0;
ss[3] = 4096;
byte[] b = new byte[8];
b[0] = (byte)(ss[0] >> 8 & 0x0FF);
b[1] = (byte)(ss[0] >> 0 & 0x0FF);
b[2] = (byte)(ss[1] >> 8 & 0x0FF);
b[3] = (byte)(ss[1] >> 0 & 0x0FF);
b[4] = (byte)(ss[2] >> 8 & 0x0FF);
b[5] = (byte)(ss[2] >> 0 & 0x0FF);
b[6] = (byte)(ss[3] >> 8 & 0x0FF);
b[7] = (byte)(ss[3] >> 0 & 0x0FF);
long l = (long)(
(b[0] << 56) |
(b[1] << 48) |
(b[2] << 40) |
(b[3] << 32) |
(b[4] << 24) |
(b[5] << 16) |
(b[6] << 8) |
(b[7] << 0));
System.out.println(Long.toString(l) + "\n");
results in a long value of 4096, which is way off. If I remove on or
the other values and replace it with 0 it still results in the same
outcome. I'm thinking there's a problem with the shifting in the 2nd to
last line, but am unable to figure it out. Any thoughts?
Here's the code:
short[] ss = new short[4];
ss[0] = 0;
ss[1] = 4096;
ss[2] = 0;
ss[3] = 4096;
byte[] b = new byte[8];
b[0] = (byte)(ss[0] >> 8 & 0x0FF);
b[1] = (byte)(ss[0] >> 0 & 0x0FF);
b[2] = (byte)(ss[1] >> 8 & 0x0FF);
b[3] = (byte)(ss[1] >> 0 & 0x0FF);
b[4] = (byte)(ss[2] >> 8 & 0x0FF);
b[5] = (byte)(ss[2] >> 0 & 0x0FF);
b[6] = (byte)(ss[3] >> 8 & 0x0FF);
b[7] = (byte)(ss[3] >> 0 & 0x0FF);
long l = (long)(
(b[0] << 56) |
(b[1] << 48) |
(b[2] << 40) |
(b[3] << 32) |
(b[4] << 24) |
(b[5] << 16) |
(b[6] << 8) |
(b[7] << 0));
System.out.println(Long.toString(l) + "\n");