bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Programming/Programming Concepts
Programming•Programming Concepts

Bitwise Operators in Programming

Bitwise operators are used to perform operations on values or variables, one bit at a time.

What is a Bitwise Operator?

A bitwise operator is a symbol or keyword that tells the computer what operation to perform, bit by bit, on values or variables.

The most common bitwise operators are

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

All data in the computer is stored as sequences of 0 s and 1 s. This makes it possible to use bitwise operators to manipulate the data.

Use the simulation below to click around and see the result of different bitwise operators:

In the simulation above, the rightmost column shows the decimal values of the variables a , b , and result . The decimal numbers are displayed to give a better understanding of what happens if you do the operation 11 & 7 (using decimal numbers), and why the result is 3 .

Left shift << , and right shift >> operators shift the bits of variable a to the left or right. The number of positions to shift is specified by second variable b , that is why variable b is limited to the first 2 bits in the simulation above.

In the example below, we use the bitwise OR operator | to combine two variables stored in binary format:

Runnable example

a = 0b1010
b = 0b0110
result = a | b
print(bin(result))

Previous

Logical Operators in Programming

Next

Comments in Programming

This chapter

Overview
25

Lessons

105m

Read time

1. Understanding The Concepts of Programming2. What is Programming ?3. Variables in Programming4. Constants in Programming5. If Statements in Programming6. Arrays in Programming7. Loops in Programming8. Functions in Programming9. Recursion in Programming10. Scope in Programming11. Strings in Programming12. Data Types in Programming13. Type Casting in Programming14. Operators in Programming15. Arithmetic Operators in Programming16. Assignment Operators in Programming17. Comparison Operators in Programming18. Logical Operators in Programming19. Bitwise Operators in Programming20. Comments in Programming21. Input and Output in Programming22. Bits and Bytes in Programming23. Binary Numbers in Programming24. Hexadecimal Numbers in Programming25. Boolean Algebra