Advanced Base Operations
Bitwise Operations in Number Bases
Bitwise Manipulation Techniques
public class BitOperationsDemo {
public static void main(String[] args) {
// Bitwise AND
int a = 0b1010; // 10 in decimal
int b = 0b1100; // 12 in decimal
int andResult = a & b;
System.out.printf("Bitwise AND: %d (Binary: %s)%n",
andResult, Integer.toBinaryString(andResult));
// Bitwise OR
int orResult = a | b;
System.out.printf("Bitwise OR: %d (Binary: %s)%n",
orResult, Integer.toBinaryString(orResult));
// Bitwise XOR
int xorResult = a ^ b;
System.out.printf("Bitwise XOR: %d (Binary: %s)%n",
xorResult, Integer.toBinaryString(xorResult));
}
}
Bitwise Operation Types
Operation |
Symbol |
Description |
Example |
AND |
& |
Bitwise conjunction |
1010 & 1100 = 1000 |
OR |
| |
Bitwise disjunction |
1010 | 1100 = 1110 |
XOR |
^ |
Exclusive OR |
1010 ^ 1100 = 0110 |
NOT |
~ |
Bitwise negation |
~1010 = 0101 |
Left Shift |
<< |
Multiply by 2^n |
1010 << 2 = 101000 |
Right Shift |
>> |
Divide by 2^n |
1010 >> 2 = 0010 |
Bit Manipulation Workflow
graph TD
A[Bit Manipulation] --> B[Bitwise Operations]
B --> C[AND Operation]
B --> D[OR Operation]
B --> E[XOR Operation]
B --> F[Shift Operations]
Advanced Bit Manipulation Techniques
Bit Masking
public class BitMaskingDemo {
public static void main(String[] args) {
// Creating a bit mask
int mask = 0b00001111; // Mask for last 4 bits
int value = 0b10101010;
// Extract last 4 bits
int extractedBits = value & mask;
System.out.printf("Extracted Bits: %d (Binary: %s)%n",
extractedBits, Integer.toBinaryString(extractedBits));
// Set specific bits
int setBitsMask = 0b00110000;
int modifiedValue = value | setBitsMask;
System.out.printf("Modified Value: %d (Binary: %s)%n",
modifiedValue, Integer.toBinaryString(modifiedValue));
}
}
Practical Applications
Bit Flags and Permissions
public class BitFlagsDemo {
// Bit flag constants
private static final int READ_PERMISSION = 1 << 0; // 1
private static final int WRITE_PERMISSION = 1 << 1; // 2
private static final int EXECUTE_PERMISSION = 1 << 2; // 4
public static void main(String[] args) {
int userPermissions = READ_PERMISSION | WRITE_PERMISSION;
// Check permissions
boolean canRead = (userPermissions & READ_PERMISSION) != 0;
boolean canWrite = (userPermissions & WRITE_PERMISSION) != 0;
boolean canExecute = (userPermissions & EXECUTE_PERMISSION) != 0;
System.out.println("Read Permission: " + canRead);
System.out.println("Write Permission: " + canWrite);
System.out.println("Execute Permission: " + canExecute);
}
}
- Bitwise operations are typically faster than arithmetic operations
- Useful for low-level system programming
- Crucial in embedded systems and performance-critical applications
Learning with LabEx
LabEx offers comprehensive environments to explore and master advanced bit manipulation techniques, helping you develop sophisticated Java programming skills.