问题
Why does the following not work? I cast an int to a byte, then shift the bits over by 7. I don't see any problems there.
However, I get the error message "possible loss of precision... required: byte; found: int"
pixels
is an array of bytes, c
is a Color object, iter
is an integer.
pixels[iter++] = ((byte) c.getRed()) << 7;
pixels[iter++] = ((byte) c.getGreen()) << 7;
pixels[iter++] = ((byte) c.getBlue()) << 7;
回答1:
In Java, the shift operators return an int
value, even if the quantity being shifted is a byte
. You need to wrap the cast to byte
around the entire expression:
pixels[iter++] = (byte) (c.getRed() << 7);
pixels[iter++] = (byte) (c.getGreen() << 7);
pixels[iter++] = (byte) (c.getBlue() << 7);
来源:https://stackoverflow.com/questions/16782412/how-to-cast-from-int-to-byte-then-use-a-bitshift-operator