Consider the following code (where byteIndex is an int):
int bitNumber = b-(8*byteIndex);
bitMask = 0x8>>(byte)bitNumber;
This generates the error
error: possible loss of precision
when compiled (required byte, found int).
The code
int bitNumber = b-(8*byteIndex);
bitMask = 0x8>>2;
compiles fine.
What is the problem here and how do I fix the first example to allow bit shifting by the int value?
EDIT: Following the comments, here is a more-complete example:
48) int byteIndex;
49) byte bitMask;
50) int bitNumber;
// assign value to byteIndex
67) bitNumber = b-(8*byteIndex);
68) bitMask = 0x8>>bitNumber;
and the error given is:
...MyClass.java:68: error: possible loss of precision
bitMask = 0x8>>bitNumber;
^
required: byte
found: int
1 error
Convert your
shiftingline to this: –Your RHS, is an int, you need to typecast it to byte..
Above code will work fine.. With or without the
castingofbitNumbertobyteSo, you can also have : –
But, here’s is a question –
byte bitMask = 0x8>>3;works fine.. Why is it so??Here’s some example to explain the reason behind its working and also the behaviour with
final: –Here’s some reasoning that explains the above behaviour: –
typecastedimplicitly only if, the compiler is sure that, it will be able to accomodate that value in thebytevariable on LHS.. Else, we have to doExplicit type castingto tell compiler that, we know what we are doing, just do it for us..Now lets consider all the cases one-by-one (From the above code (1-3, 1-2): –
varInt1initially contains 3. So the value of RHS evaluates to 64. Although this value might get accomodated tobytevariable in LHS, but compiler also knows that, it is possible to change the value ofvarInt1.. So what if value ofvarInt1is changed to 4 at some stage.. It won’t work then.. That’s why it is not allowed..Integer Literalhere, so compiler is sure that it will accomodate inbyte.. So it allows theimplicitcasting..RHSwill evaluate to128which can’t be accomodated inbyte.. Failed again..Last two cases are different from regular variables… Since they are declared
final, they can’t be re-initialized.. So, compiler can make a decision based on the assigned value..In this case, compiler sees that,
finalVarInt2contains value 3. So, RHS evaluates to 64, which can be accommodated in thebytevariable on LHS. Now, since the variable isfinalit can’t be changed, andCompilerknows that, so it is sure that t*his value will always be64*.. So compiler allows this.In the last case, value of
finalVarInt3is 4.. Similar reasoning.. Won’t fit in LHS, as RHS evaluates to 128 which can’t fit intobyte