Skip to content

Latest commit

 

History

History
70 lines (53 loc) · 2.49 KB

4.md

File metadata and controls

70 lines (53 loc) · 2.49 KB

Chapter 3: The Operator Odyssey 🤖

4 - Using Bitwise Operations

About and Using Bitwise Operators

About Bitwise Operators

Bitwise operators are used in programming to perform bitwise operations on binary numbers at the bit level. These operators manipulate individual bits of operands and are commonly used in low-level programming, embedded systems, and optimization tasks. In Linux shell scripting, bitwise operators can be used to perform bitwise AND, OR, XOR, and complement operations.

  • & (Bitwise AND)
  • | (Bitwise OR)
  • ^ (Bitwise XOR)
  • ~ (Bitwise NOT)
  • << (Left shift)
  • >> (Right shift)

Using Bitwise Operators in Linux Shell Scripting

In Linux shell scripting, you can use bitwise operators within arithmetic expressions using the (( )) construct. Here are the bitwise operators available in Bash:

  • Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits of two numbers.

    # Example: Bitwise AND operation
    (( result = 5 & 3 ))
    echo "Bitwise AND result: $result"  # Output: 1
  • Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two numbers.

    # Example: Bitwise OR operation
    (( result = 5 | 3 ))
    echo "Bitwise OR result: $result"  # Output: 7
  • Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the corresponding bits of two numbers.

    # Example: Bitwise XOR operation
    (( result = 5 ^ 3 ))
    echo "Bitwise XOR result: $result"  # Output: 6
  • Bitwise NOT (~): Performs a bitwise NOT (complement) operation, flipping all bits of a number.

    # Example: Bitwise NOT operation
    (( result = ~5 ))
    echo "Bitwise NOT result: $result"  # Output: -6
  • Bitwise Left Shift (<<): Shifts the bits of a number to the left by a specified number of positions.

    # Example: Bitwise Left Shift operation
    (( result = 5 << 1 ))
    echo "Bitwise Left Shift result: $result"  # Output: 10
  • Bitwise Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions.

    # Example: Bitwise Right Shift operation
    (( result = 5 >> 1 ))
    echo "Bitwise Right Shift result: $result"  # Output: 2

Conclusion

Bitwise operators provide a powerful way to manipulate binary data and perform operations at the bit level in Linux shell scripts.

⬅️Previous-----------Next ➡️

Table of contents 🚀