Bitwise operations in Java using byte and int
12,597
What is occurring here is binary numeric promotion. Java will promote the types of the operands for most binary operators, including the bitwise-or |
operator, to at least int
before performing the operation. The result of bitArray[i] | bitMask[j]
is an int
, not a byte
.
You must explicitly cast it back to a byte
after the operation is done.
bitArray[i] = (byte) (bitArray[i] | bitMask[j]);
Also, using the compound operator |=
means you don't have to cast back to byte
.
bitArray[i] |= bitMask[j];
Author by
ortusolis
Updated on June 04, 2022Comments
-
ortusolis almost 2 years
I'm trying to do some bitwise operations in java
I have 2 arrays:
byte[] bitArray; final byte [] bitMask = {1,2,4,8,16,32,64,-128};
then I try to
|
one byte in thebitArray
with one byte in themask
.bitArray[i] = bitArray[i] | bitMask[j]
The Problem is that I'm getting a compiler error.
"error possible loss of precision" required byte found int
The question is how can I fix it?