5

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?

Melika Barzegaran
  • 429
  • 2
  • 9
  • 25
ortusolis
  • 85
  • 1
  • 1
  • 9

1 Answers1

12

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];
rgettman
  • 176,041
  • 30
  • 275
  • 357