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

Bitwise ऑपरेटर्स

Bitwise operators किसी number के अंदर के छोटे on-off switches पर काम करते हैं, जैसे एक पंक्ति में अलग-अलग light switches flip करना। ये compact settings और 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 (&, |, ^, ~, <<, >>) integers के binary representation पर सीधे operate करते हैं। & और | हर bit पर AND/OR करते हैं, ^ XOR है, और <</>> bits को बाएं या दाएं shift करते हैं।

ये flags, masks, और low-level performance code में आम हैं।

Note: x << 1 किसी integer को double कर देता है, और x >> 1 उसे half कर देता है (non-negative numbers के लिए)।

उदाहरण: 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. #}
आम गलतियां
  1. & को && के साथ confuse करना, जबकि & integers के bits पर काम करता है और && Booleans पर।
  2. किसी negative number पर >> का उपयोग करना और zeros भरने की उम्मीद करना, जबकि >> sign बनाए रखता है और आपको >>> चाहिए।
  3. ~5 के -5 होने की उम्मीद करना, जबकि यह सभी bits को flip कर देता है और -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.