All bitwise operators in java

Java Bitwise and Bit Shift Operators with Examples

As the name itself suggests, Bitwise and Bit shift operators operates on bits( 0 and 1 ). They operates on binary representation of operands. These operators can be used with integer( byte, short, int and long ) data type variables or values only and they always returns a numerical value. Let’s see these operator types one by one.

Bitwise operators in Java

As the name itself suggests, bitwise operator performs operation bit by bit wise. Table below shows the list of all bitwise operators in java. Consider a and b as two integer type variables.

Operator Name Example Description
& Bitwise AND Operator a & b Performs bitwise AND operation between bits of a and b
| Bitwise OR Operator a | b Performs bitwise OR operation between bits of a and b
^ Bitwise XOR Operator a ^ b Performs bitwise exclusive OR operation between bits of a and b
~ Bitwise complement Operator ~ a Inverts the bits of variable a
Читайте также:  Открыть бинарный файл питон

All the bitwise operators except complement operator are binary operators. The bitwise complement operator is a unary operator, as it requires only one operand to perform the operation. It belongs to bitwise operator type because it works on bits.

Bitwise AND operator in Java

Bitwise AND( & ) operator performs bitwise AND operation on corresponding bits of both the operands. It returns 1 if both the bit’s are 1 else it returns 0 . For example & operation between two byte variable with value as 53(00110101) and 79(01001111) will result in 5(00000101) .

1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0

AND operation in java

What is the difference between & and && operator in java ?

The & operator performs bitwise AND operation on bit representation of both operands and returns an integer value while logical AND(&&) operator performs operation on two boolean expressions and returns boolean value( true or false ) as result.

Bitwise OR operator in Java

Bitwise OR( | ) operator performs bitwise OR operation on corresponding bits of both the operands. It returns 1 if any of the bit’s is 1 else it returns 0 . For example | operation between two byte variable with value as 53(00110101) and 79(01001111) will result in 127(01111111) .

1 | 1 = 1 1 | 0 = 1 0 | 1 = 1 0 | 0 = 0

or operation in java

What is the difference between bitwise OR(|) and logical OR(||) operator in java ?

The | operator performs bitwise OR operation on bit representation of both operands and returns an integer value while logical OR(||) operator performs operation on two boolean expressions and returns boolean value( true or false ) as result.

Bitwise Exclusive OR operator in Java

Bitwise XOR( ^ ) operator performs bitwise exclusive OR operation on corresponding bits of both the operands. It returns 1 if both bit’s are different else it returns 0 . For example XOR operation between two byte variable with value as 53(00110101) and 79(01001111) will result in 122(01111010) .

1 | 1 = 0 1 | 0 = 1 0 | 1 = 1 0 | 0 = 0

xor operation in java

Bitwise complement operator

The unary bitwise complement operator ~ inverts the bit pattern of an operand. It converts 0 as 1 and 1 as 0 . For example a byte data type contains 8 bits, using this operator with a byte variable with value whose bit pattern is » 00110101 » would be changed as » 11001010 «.

complement operator in java

Bitwise operator program in Java

num1 & num2 = 5
num1 | num2 = 127
num1 ^ num2 = 122
~num1 = -54

Bit Shift operator in Java

As the name itself suggests, the bit shift operators shifts the bits of an operand to left or right depending on the shift operator used. In bit shift operator, the bit pattern(operand) is given in left-side while the number of positions to shift by is given in right side of the operator. All bit shift operators are binary operators in java as they requires two operands to operate. Table below shows the list of all bit shift operators in java.

Operator Name Example Description
Signed left shift Operator a Left shifts the bits of a by 2 position
>> Signed right shift Operator a >> 3 Right shifts the bits of a by 3 position.
>>> Unsigned right shift Operator a >>> 2 Right shifts the bits of a by 2 position and places 0’s in left side.

Signed left shift operator in Java

The signed left shift operator » » shifts a bit pattern to the left by the number of positions given in the right side of this operator. It places 0 in right side for every shift. Java stores number’s in 2’s complement notation(Refer wiki for more), in which most significant bit(leftmost bit) is used for sign bit. In java, if sign bit is 0 , it means the number is positive and if it is 1 , it means the number is negative.

Using this operator a negative number can become a positive number and vice-versa. If a 0 comes into sign bit after shifting the bits of a negative number, then it becomes a positive number. Similarly if 1 comes into sign bit after shifting the bits of a positive number, then it becomes a negative number. These conditions are indications of underflow and overflow respectively.

left shift operation in java

Signed right shift operator in java

The signed right shift operator » >> » shifts a bit pattern to the right by the number of positions given in the right side of this operator. The signed right shift operator places 0 (for +ve number) or 1 (for -ve number) in left side for every shift. That is why using this operator with a positive number will always be positive while a negative number will always be negative.

right shift operation in java

Unsigned right shift operator in java

The unsigned right shift operator » >>> » shifts a bit pattern to the right by the number of positions given in the right side of this operator and places a 0 into the leftmost position in every shift, no matter whether the number is negative or positive. That is why this operator always returns a positive number.

unsigned right shift operation in java

What is the difference between signed and unsigned right shift operator ?

The only difference between signed and unsigned right shift operator is, signed right shift operator places 0 or 1 into the leftmost position depending on whether the number is positive or negative while the unsigned right shift operator always places 0 , no matter the number is positive or negative. The result of >>> operator is always a positive number while result of >> operator is positive for positive numbers and negative for negative numbers.

Bit Shift operators program in Java

class BitShiftOperatorDemo < public static void main(String[] args) < byte num1 = 53; byte num2 = -75; byte result; result = ( byte )(num1 byte )(num1 byte )(num1 >> 2); /* 00001101 = 00110101>>2 */ System.out.println( «num1 >> 2 keyword»>byte )(num1 >>> 2); /* 00001101 = 00110101>>>2 */ System.out.println( «num1 >>> 2 keyword»>int type, that is why an explicit conversion has been done in above program.

num1 num1 num1 >> 2 = 13
num1 >>> 2 = 13

  • Bitwise AND operation doesn’t mean multiplication of two number.
  • Bitwise OR operation doesn’t mean addition of two number.
  • The signed left shift
  • For positive numbers, the the result of >> and >>> operators will be same.

Источник

Java Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs the bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example
& (bitwise and) Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| (bitwise or) Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
^ (bitwise XOR) Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ (bitwise compliment) Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits. (~A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A
>> (right shift) Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111
>>> (zero fill right shift) Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111

Источник

All bitwise operators in java

«Очень интересно» . Только НЕПОНЯТНО. Зачем это нужно? Хорошо, что у нас есть Гугл, который говорит: Побитовые операции пременяются для быстрого выполнения вычислений и меньшего потребления ресурсов, связанных с этими вычислениями. Если б с этих слов начиналась статья, дальше уже хоть 100 страниц текста, читались бы на релаксе.

https://javarush.com/quests/lectures/questsyntaxpro.level08.lecture06 вот в этой лекции из квеста javarush сказано, что не все операции выполняются с лева на право, а например унарные операции выполняются с права на лево, а тут пишут — «Все операции выполняются слева направо, однако с учетом своего приоритета.» кто ошибается, подскажите пожалуйста))

Для чего нужны Сдвиги влево и в право? хоть бы один реальный пример из программы выполняющей конкретную задачу

Замечательно написано! Освежила в памяти знания, все просто понятно логично и подробно. Александр, спасибо за лекцию!

JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

Источник

Оцените статью