Java के Bitwise Operators
In this page:
int result = a & b; // also |, ^, ~
int result = a << n; // also >>, >>>
Bitwise AND and OR
Bitwise & और | किसी number की individual binary bits पर act करते हैं बजाय इसकी पूरी value के: & सिर्फ वहां एक bit रखता है जहां दोनों operands में 1 हो, जबकि | जहां भी किसी operand में 1 हो वहां एक bit सेट करता है।
उदाहरण: Bitwise AND and OR
public class Main {
public static void main(String[] args) {
int a = 6; // 110
int b = 3; // 011
System.out.println(a & b); // 2 - 1 only where both have a 1
System.out.println(a | b); // 7 - 1 where either has a 1
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise XOR (^)
^ (XOR) हर output bit को सिर्फ 1 सेट करता है जब दो input bits अलग हों -- एक classic उपयोग बिना temporary variable के दो integers swap करना है, या specific flag bits को on और off toggle करना।
उदाहरण: Bitwise XOR (^)
public class Main {
public static void main(String[] args) {
int a = 5, b = 3;
System.out.println(a ^ b); // 1 - set where bits differ
a ^= b; b ^= a; a ^= b; // classic swap without a temp variable
System.out.println(a + " " + b);
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise Complement ()
Bitwise complement operator ~ किसी number के binary representation में हर single bit flip करता है, जो signed integers के लिए mathematically -(x + 1) compute करने के बराबर है।
उदाहरण: Bitwise Complement ()
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(~x); // -6, equivalent to -(x + 1)
}
}
Login to try C/C++/Java/PHP code in the editor
Shift Operators
<< सभी bits left shift करता है, right पर zeros से भरते हुए, जो shift किए गए हर position के लिए value double करता है; >> bits right shift करता है, जो value आधा करता है (negative infinity की ओर rounding करते हुए) और दो की powers के लिए एक असली division से कहीं तेज़ है।
उदाहरण: Shift Operators
public class Main {
public static void main(String[] args) {
int x = 4;
System.out.println(x << 1); // 8 - doubles the value
System.out.println(x >> 1); // 2 - halves the value
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise Compound Assignment
Bitwise operations को assignment (&=, |=, ^=) के साथ combine करना आपको flag-style variables को in place update करने देता है, एक आम pattern जब एक single int कई true/false settings को individual bits में pack करने के लिए उपयोग होता है।
उदाहरण: Bitwise Compound Assignment
public class Main {
public static void main(String[] args) {
int flags = 0b0100;
flags |= 0b0001; // sets a bit in place
flags &= 0b0111; // clears a bit in place
System.out.println(flags);
}
}
Login to try C/C++/Java/PHP code in the editor
&को&&के साथ confuse करना, क्योंकि&integers के लिए bits पर काम करता है और booleans के लिए short-circuit नहीं करता।- यह उम्मीद करना कि
~5-5होगा, जब यह-6है। - एक बड़ी मात्रा में shift करना, जो सिर्फ low 5 bits उपयोग करता है (
intके लिए), इसलिए1 << 321है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: