Operator Bitwise Java

1. Gambaran keseluruhan

Operator digunakan dalam bahasa Java untuk beroperasi pada data dan pemboleh ubah.

Dalam tutorial ini, kita akan meneroka Pengendali Bitwise dan bagaimana mereka bekerja di Java.

2. Pengendali Bitwise

Pengendali bitwise menggunakan digit binari atau bit nilai input. Kita boleh menerapkannya pada jenis bilangan bulat - panjang, int, pendek, char dan byte.

Sebelum meneroka pengendali bitwise yang berbeza, mari kita fahami terlebih dahulu bagaimana mereka berfungsi.

Pengendali bitwise bekerja pada nombor perpuluhan bersamaan binari dan melakukan operasi pada mereka sedikit demi sedikit mengikut operator yang diberikan:

  • Pertama, operan ditukar kepada perwakilan binari mereka
  • Seterusnya, pengendali digunakan untuk setiap nombor binari dan hasilnya dikira
  • Akhirnya, hasilnya ditukar kembali ke perwakilan perpuluhannya

Mari kita fahami dengan contoh; mari kita ambil dua bilangan bulat:

int value1 = 6; int value2 = 5;

Seterusnya, mari gunakan operator ATAU pada nombor berikut:

int result = 6 | 5;

Untuk melakukan operasi ini, pertama, perwakilan binari nombor ini akan dikira:

Binary number of value1 = 0110 Binary number of value2 = 0101

Kemudian operasi akan diterapkan pada setiap bit. Hasilnya mengembalikan nombor binari baru:

0110 0101 ----- 0111

Akhirnya, hasil 0111 akan ditukar kembali ke perpuluhan yang sama dengan 7 :

result : 7

Pengendali bitwise selanjutnya dikelaskan sebagai pengendali peralihan bitwise dan operator peralihan bitwise. Mari kita perhatikan setiap jenis.

3. Pengendali Logik Bitwise

Pengendali logik bitwise adalah AND (&), OR (|), XOR (^), dan NOT (~).

3.1. Bitwise ATAU (|)

Operator OR membandingkan setiap digit binari dua integer dan memberikan kembali 1 jika salah satu daripadanya adalah 1.

Ini serupa dengan || operator logik yang digunakan dengan booleans. Apabila dua boolean dibandingkan, hasilnya adalah benar jika salah satu dari mereka benar. Begitu juga, output adalah 1 apabila salah satu daripada mereka adalah 1

Kami melihat contoh pengendali ini di bahagian sebelumnya:

@Test public void givenTwoIntegers_whenOrOperator_thenNewDecimalNumber()  value2; assertEquals(7, result); 

Mari lihat perwakilan binari operasi ini:

0110 0101 ----- 0111

Di sini, kita dapat melihat bahawa menggunakan OR, 0 dan 0 akan menghasilkan 0, sementara gabungan dengan sekurang-kurangnya 1 akan menghasilkan 1.

3.2. Sedikit demi sedikit DAN (&)

Operator AND membandingkan setiap digit binari dua integer dan memberikan kembali 1 jika kedua-duanya adalah 1, jika tidak, ia mengembalikan 0.

Ini serupa dengan operator && dengan nilai boolean . Apabila nilai dua Booleans adalah benar hasil daripada operasi && adalah benar.

Mari gunakan contoh yang sama seperti di atas, kecuali sekarang menggunakan & bukan pengganti | pengendali:

@Test public void givenTwoIntegers_whenAndOperator_thenNewDecimalNumber() { int value1 = 6; int value2 = 5; int result = value1 & value2; assertEquals(4, result); }

Mari kita lihat perwakilan binari operasi ini:

0110 0101 ----- 0100

0100 adalah 4 dalam perpuluhan, oleh itu, hasilnya adalah:

result : 4

3.3. Bitwise XOR (^)

Pengendali XOR membandingkan setiap digit binari dengan dua bilangan bulat dan memberikan kembali 1 jika kedua-dua bit yang dibandingkan berbeza. Ini bermaksud bahawa jika bit kedua-dua bilangan bulat adalah 1 atau 0 hasilnya akan menjadi 0; jika tidak, hasilnya akan menjadi 1:

@Test public void givenTwoIntegers_whenXorOperator_thenNewDecimalNumber() { int value1 = 6; int value2 = 5; int result = value1 ^ value2; assertEquals(3, result); }

Dan perwakilan binari:

0110 0101 ----- 0011

0011 adalah 3 dalam perpuluhan, oleh itu, hasilnya adalah:

result : 3

3.4. PENYELESAIAN Bitwise (~)

Pengendali Bitwise Not atau Pelengkap bermaksud penolakan setiap bit nilai input. Hanya memerlukan satu bilangan bulat dan setara dengan! pengendali.

Pengendali ini menukar setiap digit binari bilangan bulat, yang bermaksud semua 0 menjadi 1 dan semua 1 menjadi 0. The! pengendali berfungsi sama untuk nilai boolean : ia membalikkan nilai boolean dari benar ke palsu dan sebaliknya.

Sekarang mari kita fahami dengan contoh bagaimana mencari pelengkap nombor perpuluhan.

Mari lakukan pelengkap nilai1 = 6:

@Test public void givenOneInteger_whenNotOperator_thenNewDecimalNumber() { int value1 = 6; int result = ~value1; assertEquals(-7, result); }

Nilai dalam binari adalah:

value1 = 0000 0110

Dengan menggunakan operator pelengkap, hasilnya akan:

0000 0110 -> 1111 1001

This is the one’s complement of the decimal number 6. And since the first (leftmost) bit is 1 in binary, it means that the sign is negative for the number that is stored.

Now, since the numbers are stored as 2’s complement, first we need to find its 2’s complement and then convert the resultant binary number into a decimal number:

1111 1001 -> 0000 0110 + 1 -> 0000 0111

Finally, 0000 0111 is 7 in decimal. Since the sign bit was 1 as mentioned above, therefore the resulting answer is:

result : -7

3.5. Bitwise Operator Table

Let's summarize the result of the operators we've seen to so far in a comparison table:

A B A|B A&B A^B ~A 0 0 0 0 0 1 1 0 1 0 1 0 0 1 1 0 1 1 1 1 1 1 0 0

4. Bitwise Shift Operators

Binary shift operators shift all the bits of the input value either to the left or right based on the shift operator.

Let's see the syntax for these operators:

value  

The left side of the expression is the integer that is shifted, and the right side of the expression denotes the number of times that it has to be shifted.

Bitwise shift operators are further classified as bitwise left and bitwise right shift operators.

4.1. Signed Left Shift [<<]

The left shift operator shifts the bits to the left by the number of times specified by the right side of the operand. After the left shift, the empty space in the right is filled with 0.

Another important point to note is that shifting a number by one is equivalent to multiplying it by 2, or, in general, left shifting a number by n positions is equivalent to multiplication by 2^n.

Let's take the value 12 as the input value.

Now, we will move it by 2 places to the left (12 <<2) and see what will be the final result.

The binary equivalent of 12 is 00001100. After shifting to the left by 2 places, the result is 00110000, which is equivalent to 48 in decimal:

@Test public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() { int value = 12; int leftShift = value << 2; assertEquals(48, leftShift); } 

This works similarly for a negative value:

@Test public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() { int value = -12; int leftShift = value << 2; assertEquals(-48, leftShift); }

4.2. Signed Right Shift [>>]

The right shift operator shifts all the bits to the right. The empty space in the left side is filled depending on the input number:

  • When an input number is negative, where the leftmost bit is 1, then the empty spaces will be filled with 1
  • When an input number is positive, where the leftmost bit is 0, then the empty spaces will be filled with 0

Let's continue the example using 12 as input.

Now, we will move it by 2 places to the right(12 >>2) and see what will be the final result.

The input number is positive, so after shifting to the right by 2 places, the result is 0011, which is 3 in decimal:

@Test public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() { int value = 12; int rightShift = value >> 2; assertEquals(3, rightShift); }

Also, for a negative value:

@Test public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() { int value = -12; int rightShift = value >> 2; assertEquals(-3, rightShift); }

4.3. Unsigned Right Shift [>>>]

This operator is very similar to the signed right shift operator. The only difference is that the empty spaces in the left are filled with 0 irrespective of whether the number is positive or negative. Therefore, the result will always be a positive integer.

Let's right shift the same value of 12:

@Test public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() { int value = 12; int unsignedRightShift = value >>> 2; assertEquals(3, unsignedRightShift); }

And now, the negative value:

@Test public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() { int value = -12; int unsignedRightShift = value >>> 2; assertEquals(1073741821, unsignedRightShift); }

5. Difference Between Bitwise and Logical Operators

There are a few differences between the bitwise operators we've discussed here and the more commonly known logical operators.

First, logical operators work on boolean expressions and return boolean values (either true or false), whereas bitwise operators work on binary digits of integer values (long, int, short, char, and byte) and return an integer.

Also, logical operators always evaluate the first boolean expression and, depending on its result and the operator used, may or may not evaluate the second. On the other hand, bitwise operators always evaluate both operands.

Finally, logical operators are used in making decisions based on multiple conditions, while bitwise operators work on bits and perform bit by bit operations.

6. Kes Penggunaan

Beberapa kes penggunaan berpotensi operator bitwise adalah:

  • Stack komunikasi di mana bit individu di header yang dilampirkan pada data menandakan maklumat penting
  • Dalam sistem tertanam untuk menetapkan / membersihkan / menukar hanya satu bit dari daftar tertentu tanpa mengubah bit yang tinggal
  • Untuk menyulitkan data untuk masalah keselamatan menggunakan operator XOR
  • Dalam pemampatan data dengan menukar data dari satu perwakilan ke yang lain, untuk mengurangkan jumlah ruang yang digunakan

7. Kesimpulannya

Dalam tutorial ini, kami mengetahui tentang jenis operator bitwise dan bagaimana mereka berbeza dengan operator logik. Kami juga melihat beberapa kes penggunaan yang berpotensi untuk mereka.

Semua contoh kod dalam artikel ini terdapat di GitHub.