Practical Conversion Examples
Real-World Conversion Scenarios
Network Address Conversion
public class NetworkUtils {
public static String ipToHex(String ipAddress) {
String[] octets = ipAddress.split("\\.");
StringBuilder hexIP = new StringBuilder();
for (String octet : octets) {
int decimal = Integer.parseInt(octet);
String hex = String.format("%02X", decimal);
hexIP.append(hex);
}
return hexIP.toString();
}
public static void main(String[] args) {
String ip = "192.168.1.1";
String hexIP = ipToHex(ip);
System.out.println("Hex IP: " + hexIP);
}
}
Cryptographic Applications
Base Encoding Techniques
import java.util.Base64;
public class EncodingExample {
public static String convertToBase64(String input) {
return Base64.getEncoder().encodeToString(input.getBytes());
}
public static String decodeFromBase64(String base64Input) {
byte[] decodedBytes = Base64.getDecoder().decode(base64Input);
return new String(decodedBytes);
}
}
Data Validation and Conversion
public class InputValidator {
public static boolean isValidBase(String number, int base) {
try {
Integer.parseInt(number, base);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static int safeConvert(String number, int base) {
return isValidBase(number, base)
? Integer.parseInt(number, base)
: -1;
}
}
Conversion Workflow
graph TD
A[Input Data] --> B{Validate Input}
B --> |Valid| C[Choose Conversion Method]
B --> |Invalid| D[Error Handling]
C --> E[Perform Conversion]
E --> F[Output Converted Data]
Common Conversion Patterns
Source Base |
Target Base |
Use Case |
Decimal |
Binary |
Low-level programming |
Decimal |
Hexadecimal |
Color codes, Memory addresses |
Binary |
Hexadecimal |
Network protocols |
Advanced Conversion Techniques
Custom Base Conversion
public class CustomBaseConverter {
private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String convertToBase(int number, int base) {
if (base < 2 || base > 36) {
throw new IllegalArgumentException("Invalid base");
}
if (number == 0) return "0";
StringBuilder result = new StringBuilder();
boolean negative = number < 0;
number = Math.abs(number);
while (number > 0) {
result.insert(0, DIGITS.charAt(number % base));
number /= base;
}
return negative ? "-" + result : result.toString();
}
}
- Use built-in methods for standard conversions
- Implement custom methods for specialized requirements
- Consider input validation and error handling
Note: LabEx encourages developers to practice these conversion techniques to enhance their Java programming skills.