Operadores Java Bitwise e Shift (com exemplos)

Neste tutorial, aprenderemos sobre o operador bit a bit e diferentes tipos de operadores shift em Java com a ajuda de exemplos.

Em Java, os operadores bit a bit executam operações em dados inteiros no nível de bit individual. Aqui, os dados inteiro inclui byte, short, int, e longtipos de dados.

Existem 7 operadores para realizar operações em nível de bit em Java.

Operador Descrição
| OR bit a bit
& E bit a bit
^ XOR bit a bit
~ Complemento bit a bit
<< Desvio à esquerda
>> Shift à direita assinado
>>> Shift direito sem sinal

1. Operador Java Bitwise OR

O |operador OR bit a bit retorna 1 se pelo menos um dos operandos for 1. Caso contrário, ele retorna 0.

A seguinte tabela verdade demonstra o funcionamento do operador OR bit a bit. Sejam aeb dois operandos que podem assumir apenas valores binários, ou seja, 1 ou 0.

uma b a | b
0 0 0
0 1 1
1 0 1
1 1 1

A tabela acima é conhecida como "Tabela da verdade" para o operador OR bit a bit.

Vejamos a operação OR bit a bit de dois inteiros 12 e 25.

 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR Operation of 12 and 25 00001100 | 00011001 ____________ 00011101 = 29 (In Decimal)

Exemplo 1: bit a bit OR

 class Main ( public static void main(String() args) ( int number1 = 12, number2 = 25, result; // bitwise OR between 12 and 25 result = number1 | number2; System.out.println(result); // prints 29 ) )

2. Operador Java bit a bit AND

O &operador AND bit a bit retorna 1 se e somente se ambos os operandos são 1. Caso contrário, ele retorna 0.

A tabela a seguir demonstra o funcionamento do operador AND bit a bit. Sejam aeb dois operandos que só podem assumir valores binários, ou seja, 1 e 0.

uma b a e b
0 0 0
0 1 0
1 0 0
1 1 1

Vamos dar uma olhada na operação AND bit a bit de dois inteiros 12 e 25.

 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) // Bitwise AND Operation of 12 and 25 00001100 & 00011001 ____________ 00001000 = 8 (In Decimal)

Exemplo 2: bit a bit AND

  class Main ( public static void main(String() args) ( int number1 = 12, number2 = 25, result; // bitwise AND between 12 and 25 result = number1 & number2; System.out.println(result); // prints 8 ) )

3. Operador Java Bitwise XOR

O ^operador XOR bit a bit retorna 1 se e somente se um dos operandos for 1. No entanto, se ambos os operandos forem 0 ou se ambos forem 1, o resultado será 0.

A seguinte tabela verdade demonstra o funcionamento do operador XOR bit a bit. Sejam aeb dois operandos que podem assumir apenas valores binários, ou seja, 1 ou 0.

uma b a e b
0 0 0
0 1 1
1 0 1
1 1 0

Vejamos a operação XOR bit a bit de dois inteiros 12 e 25.

 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) // Bitwise XOR Operation of 12 and 25 00001100 00011001 ____________ 00010101 = 21 (In Decimal)

Exemplo 4: XOR bit a bit

 class Main ( public static void main(String() args) ( int number1 = 12, number2 = 25, result; // bitwise XOR between 12 and 25 result = number1 number2; System.out.println(result); // prints 21 ) )

4. Operador Java Bitwise Complement

O operador de complemento bit a bit é um operador unário (funciona com apenas um operando). É denotado por ~.

Ele muda os dígitos binários de 1 para 0 e 0 para 1 .

Operador Java Bitwise Complement

It is important to note that the bitwise complement of any integer N is equal to - (N + 1). For example,

Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36. Now let's see if we get the correct answer or not.

 35 = 00100011 (In Binary) // using bitwise complement operator ~ 00100011 __________ 11011100

In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we convert the result into decimal we get 220.

However, it is important to note that we cannot directly convert the result into decimal and get the desired output. This is because the binary result 11011100 is also equivalent to -36.

To understand this we first need to calculate the binary output of -36.

2's Complement

In binary arithmetic, we can calculate the binary negative of an integer using 2's complement.

1's complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the 1's complement, we get the 2's complement of the original number. For example,

 // compute the 2's complement of 36 36 = 00100100 (In Binary) 1's complement = 11011011 2's complement: 11011011 + 1 _________ 11011100

Aqui, podemos ver que o complemento de 2 de 36 (ou seja, -36 ) é 11011100 . Este valor é equivalente ao complemento bit a bit de 35 .

Portanto, podemos dizer que o complemento bit a bit de 35 é - (35 + 1) = -36 .

Exemplo 3: Complemento bit a bit

 class Main ( public static void main(String() args) ( int number = 35, result; // bitwise complement of 35 result = ~number; System.out.println(result); // prints -36 ) )

Operadores Java Shift

Existem três tipos de operadores de turno em Java:

  • Shift à esquerda assinado (<<)
  • Shift para a direita assinado (>>)
  • Shift direito sem sinal (>>>)

5. Operador Java Left Shift

O operador de deslocamento para a esquerda desloca todos os bits para a esquerda por um certo número de bits especificados. É denotado por <<.

Operador Java 1 bit Left Shift

As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.

As a result, the left-most bit (most-significant) is discarded and the right-most position(least-significant) remains vacant. This vacancy is filled with 0s.

Example 5: Left Shift Operators

 class Main ( public static void main(String() args) ( int number = 2; // 2 bit left shift operation int result = number << 2; System.out.println(result); // prints 8 ) )

5. Java Signed Right Shift Operator

The signed right shift operator shifts all bits towards the right by a certain number of specified bits. It is denoted by >>.

When we shift any number to the right, the least significant bits (rightmost) are discarded and the most significant position (leftmost) is filled with the sign bit. For example,

 // right shift of 8 8 = 1000 (In Binary) // perform 2 bit right shift 8>> 2: 1000>> 2 = 0010 (equivalent to 2)

Aqui, estamos realizando o deslocamento à direita de 8 (ou seja, o sinal é positivo). Portanto, não há bit de sinal. Portanto, os bits mais à esquerda são preenchidos com 0 (representa o sinal positivo).

 // right shift of -8 8 = 1000 (In Binary) 1's complement = 0111 2's complement: 0111 + 1 _______ 1000 Signed bit = 1 // perform 2 bit right shift 8>> 2: 1000>> 2 = 1110 (equivalent to -2)

Aqui, usamos o bit 1 com sinal para preencher os bits mais à esquerda.

Exemplo 6: Operador de mudança à direita com sinal

 class Main ( public static void main(String() args) ( int number1 = 8; int number2 = -8; // 2 bit signed right shift System.out.println(number1>> 2); // prints 2 System.out.println(number2>> 2); // prints -2 ) )

7. Operador de deslocamento direito sem sinal Java

Java também fornece um deslocamento para a direita sem sinal. É denotado por >>>.

Aqui, a posição vaga mais à esquerda é preenchida com 0 em vez do bit de sinal. Por exemplo,

 // unsigned right shift of 8 8 = 1000 8>>> 2 = 0010 // unsigned right shift of -8 -8 = 1000 (see calculation above) -8>>> 2 = 0010

Exemplo 7: deslocamento para a direita sem sinal

 class Main ( public static void main(String() args) ( int number1 = 8; int number2 = -8; // 2 bit signed right shift System.out.println(number1>>> 2); // prints 2 System.out.println(number2>>> 2); // prints 1073741822 ) )

Como podemos ver, o operador de deslocamento para a direita com e sem sinal retorna resultados diferentes para bits negativos. Para saber mais visite a Diferença entre >> e >>>.

Artigos interessantes...