Search⌘ K

Bitwise negation

Explore bitwise negation in Bash, where each bit of a number is inverted using the tilde symbol. Understand how Bash handles signed and unsigned integers, how the number's memory representation influences results, and how to interpret outputs with echo and printf commands. This lesson helps you grasp critical details of bitwise operations for effective Bash scripting.

Bitwise operations handle each bit of a number individually. We use them often when programming. Let’s consider how they work in detail.

Bitwise negation

First, we will consider the simplest bitwise operation: negation. It is also called bitwise NOT. The tilde symbol (~) indicates this operation in Bash.

When doing bitwise negation, we swap the value of each bit of an integer. This means that we replace each 1 to 0, and vice versa.

Here is an example of doing bitwise NOT for the number 5:

5 = 101
~5 = 010

The bitwise NOT is a simple operation when we talk about mathematics. However, there are pitfalls when we use it in programming. We should keep two ...