Using the Bitwise Logical Operators
By: aathishankaran Printer Friendly Format
Using the Bitwise Logical Operators
The following program demonstrates the Bitwise logical operators:
//Demonstrate
the Bitwise logical operators
class
BitLogic {
public static void main (String args[]) {
String binary[] = {
“0000â€,
“0001â€, “0010â€, “0011â€, “0100â€, “0101â€, “0110â€,
“0111â€,
“1000â€,
“1001â€, “1010â€, “1011â€, “1100â€, “1101â€, “1110â€,
“1111â€
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0011 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = ( ~a & b) | ( a
& ~b);
int g = ~a & 0x0f;
System.out.println(“
a = “ + binary[a]);
System.out.println(“
b = “ + binary[b]);
System.out.println(“
a | b = “ + binary[a]);
System.out.println(“
a & b = “ + binary[a]);
System.out.println(“
a ^ b = “ + binary[a]);
System.out.println(“~a&b
| a&~b = “ + binary[a]);
System.out.println(“
~a = “ + binary[a]);
}
}
In this example, a and b has bit patterns, which present all four possibilities for two binary digits: 0-0, 0-1, 1-0, and 1-1. You can see how the | and & operate on each bit by the results in c and d. The values assigned to e and f are the same and illustrate how the ^ works. The string array named binary holds the human-readable, binary representation of the numbers 0 through 15. in this example, the array is indexed to show the binary representation of each result. The array is constructed such that the correct string representation of a binary value n is stored in binary [n]. The value of ~a is ANDed with 0x0f (0000 1111 in binary) in order to reduce its value to less than 16, so it can be printed by use of the binary array. Here is the output from this program.
a = 0011
b = 0011
a | b = 0011
a & b = 0011
a ^ b = 0011
~a&b | a&~b = 0011
~a = 0011
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java