Bit Shifting wrong value

I have a problem, I need to convert coordinates using shift, and after that convert them back to original but it returns not the same value (min,max values can't be changed..).

int x = 1000;
int y = -1000;

int minx = -294912; // can't be changed.
int miny = -262144; // can't be changed.

//Convert
int convertedX = x - minx >> 4;
int convertedY = y - miny >> 4;

//Convert back
int originalX = (convertedX << 4) + minx;
int originalY = (convertedY << 4) + miny;

System.out.println(originalX + " " + originalY + " - After Convert Back");
Jon Skeet
people
quotationmark

The problem is that your shift is effectively dividing by 16... so you end up losing information. You can't exactly represent any values which aren't exactly divisible by 16 (i.e. values which don't have the bottom four bits as 0000.)

If you don't want to lose information, you can't apply that shift - it's as simple as that.

(Personally I'd also put brackets around x - minx to make the precedence clear. That isn't actually causing you problems, but unless people have learned the precedence rules, the code isn't clear.)

people

See more on this question at Stackoverflow