Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations in Java using byte and int [duplicate]

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?

like image 811
ortusolis Avatar asked Mar 05 '15 22:03

ortusolis


People also ask

What is this >>> Bitwise operator in Java?

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.

How bitwise operators work 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.

What are bitwise operators and explain each with an example in Java?

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.

How do you double a number in bitwise?

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.


1 Answers

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];
like image 73
rgettman Avatar answered Sep 17 '22 02:09

rgettman