Reputation: 91
I have question regarding my code here:
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World\n");
int x = 36;
byte b1 = ((byte) x) & ((byte) 0xff); // it seems it is the part after &, but I have 0xff cast to byte by using (byte)0xff, so not sure where exactly the error is coming from.
System.out.println(b1);
}
}
I am not sure exactly which part is causing the error of:
incompatible types: possible lossy conversion from int to byte
This is the error message output from the program:
Upvotes: 0
Views: 633
Reputation: 448
To compute x & y
where the two operands are bytes, they must first be promoted to int
values. There is no &
between bytes. The result is therefore of type int
That is, what you wrote is effectively evaluated as if you'd written it as the following, making explicit what the language gives you implicitly:
byte b1 = ((int) (byte) x) & ((int) (byte) 0xff);
Just do the arithmetic and then cast the result to byte
.
byte b1 = (byte)(x & 0xff);
Link to Java Language Specification
Edited to add, thanks to @rzwitserloot, that masking a byte value with 0xff is however pointless. If you need the assignment from an integer to a byte, just write the cast:
byte b1 = (byte)x;
Upvotes: 0
Reputation: 102830
You appear to be confused.
There is no point in your code. taking any number, calculating that & 0xFF
, and then storing it in a byte, is always a noop - it does nothing.
You additionally get an error because &
inherently always produces at least an int
(it'll upcast anything smaller to match), so you're trying to assign an int to a byte.
What are you trying to accomplish?
No can do. Java doesn't have unsigned bytes. A java byte is signed. Period. It can hold a value between -128 and +127. For calculation purposes, -128 and 255 are identical (they are both the bit sequence 1111 1111
- in hex, 0xFF
, and they act identically under all relevant arithmetic, though it does get tricky when converting them to another numeric type int
).
Then use int
. This is where most & 0xFF
you'll ever see in java code comes from: When you have a byte value which java inherently treats as signed, but you wish to treat it as unsigned and, therefore (given that in java bytes can't do that), you want to upcast it to an int, containing the unsigned representation. This is how to do that:
int x = y & 0xFF;
Where y
is any byte.
You presumably saw this somewhere and are now trying to apply it, but assigning the result of y & 0xFF
to a byte
doesn't mean anything. You'd assign it to an int
variable, or just use it as expression in a further calculation (y & 0xFF
is an int
- make sure you add the appropriate parentheses, &
has perhaps unexpected precedence).
int x = 36;
byte b1 = ((byte) x) & ((byte) 0xff);
Every imaginable way of this actually working would mean that b1
is... still 36.
Upvotes: 1