Java Tutorials - Herong's Tutorial Examples - v8.22, by Herong Yang
Bitwise Operations on "byte" Values - Example Program
This section provides a tutorial example on how 4 types of bitwise operations, 'And', 'Or', 'Exclusive Or', and 'Complement' works on 'int' values.
To verify those bitwise operation rules given in the previous section, I wrote the following test program, BitwiseOperations.java:
/* BitwiseOperations.java * Copyright (c) HerongYang.com. All Rights Reserved. */ public class BitwiseOperations { public static void main(String[] arg) { int a = 858993459; // binary: 00110011001100110011001100110011 int b = 1431655765; // binary: 01010101010101010101010101010101 int o1 = a & b; // bitwise "And" int o2 = a | b; // bitwise "Or" int o3 = a ^ b; // bitwise "Exclusive Or" int o4 = ~a; // bitwise "Complement" System.out.println(" a: "+getBitString(a) +" = "+a); System.out.println(" b: "+getBitString(b) +" = "+b); System.out.println("o1: "+getBitString(o1) +" = "+o1); System.out.println("o2: "+getBitString(o2) +" = "+o2); System.out.println("o3: "+getBitString(o3) +" = "+o3); System.out.println("o4: "+getBitString(o4) +" = "+o4); } private static String getBitString(int x) { StringBuffer buf = new StringBuffer(); for (int i=1; i<=32; i++) buf.append(x>>>(32-i) & 0x00000001); return buf.toString(); } }
Here is the output of the test program:
a: 00110011001100110011001100110011 = 858993459 b: 01010101010101010101010101010101 = 1431655765 o1: 00010001000100010001000100010001 = 286331153 o2: 01110111011101110111011101110111 = 2004318071 o3: 01100110011001100110011001100110 = 1717986918 o4: 11001100110011001100110011001100 = -858993460
The resulting values in the program output do match those given in my examples in the previous section. The resulting value of the complement operation in the program output shows -858993460, which is the same as 3233857728 represented in a signed 32-bit integer format.
Table of Contents
Execution Process, Entry Point, Input and Output
Primitive Data Types and Literals
►Bits, Bytes, Bitwise and Shift Operations
"byte" Data Type and Implicit Casting
Operations on "byte" Data Type Values
Bitwise Operations on "byte" Values
►Bitwise Operations on "byte" Values - Example Program
Shift Operations - Left, Right or Unsigned Right
Managing Bit Strings in Byte Arrays
Reference Data Types and Variables
StringBuffer - The String Buffer Class
System Properties and Runtime Object Methods
Generic Classes and Parameterized Types
Generic Methods and Type Inference
Lambda Expressions and Method References
Java Modules - Java Package Aggregation
Execution Threads and Multi-Threading Java Programs
ThreadGroup Class and "system" ThreadGroup Tree
Synchronization Technique and Synchronized Code Blocks
Deadlock Condition Example Programs
Garbage Collection and the gc() Method
Assert Statements and -ea" Option