Code Implementation Examples
Comprehensive Binary Conversion Scenarios
1. Basic Integer Array Conversion
public class IntegerToBinaryConverter {
public static String[] convertIntegersToBinary(int[] numbers) {
return Arrays.stream(numbers)
.mapToObj(Integer::toBinaryString)
.toArray(String[]::new);
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
String[] binaryRepresentations = convertIntegersToBinary(numbers);
for (int i = 0; i < numbers.length; i++) {
System.out.printf("%d → %s%n", numbers[i], binaryRepresentations[i]);
}
}
}
2. Custom Binary Conversion with Padding
public class PaddedBinaryConverter {
public static String convertWithPadding(int number, int bitLength) {
return String.format("%" + bitLength + "s",
Integer.toBinaryString(number))
.replace(' ', '0');
}
public static void main(String[] args) {
int[] numbers = {5, 15, 25};
int bitLength = 8;
for (int num : numbers) {
System.out.println(convertWithPadding(num, bitLength));
}
}
}
Conversion Techniques Workflow
graph TD
A[Input Integer] --> B{Conversion Method}
B --> |Built-in Method| C[Integer.toBinaryString()]
B --> |Custom Method| D[Manual Bitwise Conversion]
C --> E[Binary String Output]
D --> E
3. Advanced Binary Manipulation
public class BinaryManipulator {
public static String[] generateBinarySequence(int start, int end) {
return IntStream.rangeClosed(start, end)
.mapToObj(Integer::toBinaryString)
.toArray(String[]::new);
}
public static boolean isBinaryPalindrome(String binaryString) {
return binaryString.equals(new StringBuilder(binaryString).reverse().toString());
}
public static void main(String[] args) {
String[] binarySequence = generateBinarySequence(1, 10);
System.out.println("Binary Palindromes:");
Arrays.stream(binarySequence)
.filter(BinaryManipulator::isBinaryPalindrome)
.forEach(System.out::println);
}
}
Conversion Method Complexity
Method |
Time Complexity |
Space Complexity |
Flexibility |
Integer.toBinaryString() |
O(log n) |
O(1) |
Low |
Stream Conversion |
O(n log n) |
O(n) |
Medium |
Manual Bitwise |
O(log n) |
O(1) |
High |
Key Takeaways
- Use built-in methods for simple conversions
- Implement custom methods for specific requirements
- Consider performance and memory constraints
- Understand bitwise operations
At LabEx, we emphasize practical implementation and deep understanding of binary conversion techniques in Java programming.