簡體   English   中英

如何從int轉換為字節,然后使用位移運算符

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

為什么以下方法不起作用? 我將整數轉換為一個字節,然后將這些位移了7。我看不到那里有任何問題。

但是,我收到錯誤消息“可能丟失精度...必需:字節;發現:int”

pixels是字節數組, c是Color對象, iter是整數。

pixels[iter++] = ((byte) c.getRed()) << 7;
pixels[iter++] = ((byte) c.getGreen()) << 7;
pixels[iter++] = ((byte) c.getBlue()) << 7;

在Java中,即使要移位的數量為byte ,移位運算符也會返回int值。 您需要將強制轉換包裝到整個表達式的byte周圍:

pixels[iter++] = (byte) (c.getRed() << 7);
pixels[iter++] = (byte) (c.getGreen() << 7);
pixels[iter++] = (byte) (c.getBlue() << 7);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM