Unlocking the Power of Bitwise Operations in Kotlin

Bitwise Operations: The Unseen Heroes of Coding

When it comes to performing bit-level operations in Kotlin, bitwise and bit shift operators are the unsung heroes. These operators work on two integral types, Int and Long, to execute operations that are essential for any programming task. But how do they work, and what are their functions?

The OR Operator: A Logic Gate

The OR operator is a logic gate that compares corresponding bits of two values. If either of the bits is 1, it returns 1. Otherwise, it returns 0. This operator is useful when you need to perform a logical OR operation between two binary numbers.

Example: val result = 5 or 3

Output: 7

The AND Operator: A Filter

The AND operator is a filter that compares corresponding bits of two values. If both bits are 1, it returns 1. Otherwise, it returns 0. This operator is useful when you need to perform a logical AND operation between two binary numbers.

Example: val result = 5 and 3

Output: 1

The XOR Operator: A Toggle

The XOR operator is a toggle that compares corresponding bits of two values. If the corresponding bits are different, it returns 1. Otherwise, it returns 0. This operator is useful when you need to perform a logical XOR operation between two binary numbers.

Example: val result = 5 xor 3

Output: 6

The Inverse Operator: A Bit Flipper

The inverse operator flips every bit of a binary number. It makes every 0 a 1 and every 1 a 0. This operator is useful when you need to invert a binary number.

Example: val result = 35.inv()

Output: -36

But why do we get -36 instead of 220? It’s because the compiler shows the 2’s complement of the number, which is a negative notation of the binary number.

Shifting Bits: The Left Shift Operator

The left shift operator shifts the bit pattern to the left by a specified number of bits. Zero bits are shifted into the low-order positions.

Example: val result = 5 shl 2

Output: 20

Shifting Bits: The Right Shift Operator

The right shift operator shifts the bit pattern to the right by a specified number of bits. If the number is a 2’s complement signed number, the sign bit is shifted into the high-order positions.

Example: val result = 10 shr 2

Output: 2

Shifting Bits: The Unsigned Right Shift Operator

The unsigned right shift operator shifts zero into the leftmost position. This operator is useful when you need to perform an unsigned right shift operation.

Example: val result = 2147483645 ushr 2

Output: 536870912

Notice how the signed and unsigned right shift operators work differently for 2’s complement numbers.

Mastering Bitwise Operations

By mastering bitwise operations, you can unlock the full potential of Kotlin programming. These operators may seem complex at first, but with practice and patience, you can become a pro at using them to perform complex operations with ease.

Leave a Reply

Your email address will not be published. Required fields are marked *