How to cast from int to byte, then use a bitshift operator

烈酒焚心 提交于 2019-12-13 06:24:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!