Practical Binary Conversion
Comprehensive Binary Conversion Strategies
1. Decimal to Binary Conversion
public class DecimalToBinaryConverter {
public static String convertDecimalToBinary(int decimal) {
if (decimal == 0) return "0";
StringBuilder binary = new StringBuilder();
while (decimal > 0) {
binary.insert(0, decimal % 2);
decimal /= 2;
}
return binary.toString();
}
public static void main(String[] args) {
int[] numbers = {10, 25, 42, 100};
for (int num : numbers) {
System.out.println(num + " â " + convertDecimalToBinary(num));
}
}
}
2. Binary to Decimal Conversion
graph TD
A[Binary to Decimal] --> B[Positional Value Calculation]
B --> C[Multiply Each Digit by Power of 2]
B --> D[Sum the Resulting Values]
public class BinaryToDecimalConverter {
public static int convertBinaryToDecimal(String binary) {
int decimal = 0;
int power = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += Math.pow(2, power);
}
power++;
}
return decimal;
}
public static void main(String[] args) {
String[] binaryNumbers = {"1010", "11001", "101010"};
for (String binary : binaryNumbers) {
System.out.println(binary + " â " + convertBinaryToDecimal(binary));
}
}
}
Conversion Techniques Comparison
Conversion Type |
Method |
Complexity |
Performance |
Decimal to Binary |
Repeated Division |
O(log n) |
Efficient |
Binary to Decimal |
Positional Calculation |
O(n) |
Linear |
Bitwise Conversion |
Bitwise Operators |
O(1) |
Fastest |
3. Advanced Bitwise Conversion
public class BitwiseConverter {
// Bitwise method for binary representation
public static String intToBinary(int number) {
return String.format("%32s", Integer.toBinaryString(number)).replace(' ', '0');
}
// Count set bits (1s) in a number
public static int countSetBits(int number) {
int count = 0;
while (number != 0) {
count += number & 1;
number >>>= 1;
}
return count;
}
public static void main(String[] args) {
int testNumber = 42;
System.out.println("Binary Representation: " + intToBinary(testNumber));
System.out.println("Set Bits Count: " + countSetBits(testNumber));
}
}
Practical Applications
Use Cases for Binary Conversion
- Network protocol implementation
- Cryptography
- Low-level system programming
- Bitwise operation optimization
LabEx Recommendation
At LabEx, we emphasize understanding binary conversion as a fundamental skill for advanced programming and system-level development.
Error Handling in Conversions
public class SafeBinaryConverter {
public static int safeBinaryToDecimal(String binary) {
try {
return Integer.parseInt(binary, 2);
} catch (NumberFormatException e) {
System.err.println("Invalid binary string: " + binary);
return 0;
}
}
}
Key Takeaways
- Understand multiple conversion methods
- Use appropriate techniques for different scenarios
- Consider performance and readability
- Implement robust error handling