← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 4 of 7

Bitwise Operators

Bitwise operators work on the tiny on-off switches inside a number, like flipping single light switches in a row. They are used for compact settings and low-level tricks.

In this page:

  1. Bitwise Operators
Syntax
scala
a & b
a | b
a ^ b
~a
a << n
a >> n

Bitwise Operators

Bitwise operators (&, |, ^, ~, <<, >>) operate directly on the binary representation of integers. & and | perform AND/OR on each bit, ^ is XOR, and <</>> shift bits left or right.

They're common in flags, masks, and low-level performance code.

Note: x << 1 doubles an integer, and x >> 1 halves it (for non-negative numbers).

Example: Bitwise Operators

markup
object Main extends App {
  val a = 6 // 110
  val b = 3 // 011

  println(a & b)  // 010 = 2
  println(a | b)  // 111 = 7
  println(a ^ b)  // 101 = 5
  println(a << 1) // 1100 = 12
  println(a >> 1) // 011 = 3
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Confusing & with &&, when & works on the bits of integers and && on Booleans.
  2. Using >> on a negative number and expecting zeros to fill in, when >> keeps the sign and you need >>>.
  3. Expecting ~5 to be -5, when it flips all bits and gives -6.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.