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];
Share:
12,597
ortusolis
Author by

ortusolis

Updated on June 04, 2022

Comments

  • ortusolis
    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 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?