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 the bitArray
with one byte in the mask
.
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?
In Java, bitwise operators perform operations on integer data at the individual bit-level. Here, the integer data includes byte , short , int , and long types of data. There are 7 operators to perform bit-level operations in Java.
Bitwise operators work on a binary equivalent of decimal numbers and perform operations on them bit by bit as per the given operator: First, the operands are converted to their binary representation. Next, the operator is applied to each binary number and the result is calculated.
Bitwise Complement (~) This operator is a unary operator, denoted by '~. ' It returns the one's complement representation of the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. Note: Compiler will give 2's complement of that number, i.e., 2's complement of 10 will be -6.
A number can be multiplied by 2 using bitwise operators. This is done by using the left shift operator and shifting the bits left by 1. This results in double the previous number.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With