I have this code
byte[] b = new byte[]{-33,-4,20,30};
System.err.println(Arrays.toString(b));
int x = (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + b[3];
b = new byte[]{(byte)(x >> 24), (byte)(x >> 16), (byte)(x >> 8), (byte)(x)};
System.err.println(Arrays.toString(b));
Output:
[-33, -4, 20, 30]
[-34, -4, 20, 30]
I cannot figure out why this operations are not invers.
Your problem is unwanted sign extension.
Specifically,
b[1]is-4, or0xfcwhich is sign-extended to0xfffffffcthen left-shifted to0xfffc0000. This has the effect of decrementing the most-significant byte by 1.Try: