I'm very new to Java, so please bear with me. I am trying to make a small plugin for the ImageJ program. I've successfully used some sample code to read the pixels of a 16-bit image into a short array.
short pixels = (short)ip.getPixels();
I need to do some calculations on the pixels, and I would like to convert them to integers so the range is 0-65,535 instead of -32,768 to 32,767.
I found a tutorial that recommends the following to convert the short array into int:
int pix = pixels[i] & 0xffff;
However, when I sum the pixels:
int sumPix = 0;
sumPix = sumPix + pix;
I still end up with a negative number. I thought the " & 0xffff " should remove the sign and leave me with only positive integers.
I've attached the full .java file. Please focus on how to obtain a positive integer value for the sum of the array. I realize some of the other code may not be the ideal way to approach this, but I am trying to learn one thing at a time.
I should mention I've also tried pixels[i].intValue() - this raises an error in the compiler. I believe it is because pixels[i] is a primitive and not an object.
Thank you so much for the quick and helpful response. I didn't consider overflowing int, but I see that is what's happening. My calculations will include quotients that will introduce decimals, so I am planning on using double to store these. Is there any reason not to convert the short directly into a double even though it won't have a decimal? Should I use long?
Believe it or not, the absolute highest number that can be represented by a float is... Infinity. I am not kidding. The next highest value is... 3.40282346638528860 times 10 to the 38th power. Regardless, it means that it is not possible to overflow a float, by adding a small (short) number, and get a negative sum.
You can, however, lose precision. It is possible to have the sum be so large, that adding a small number to it, will have no effect.