实际的二进制转换
全面的二进制转换策略
1. 十进制转二进制转换
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. 二进制转十进制转换
graph TD
A[二进制转十进制] --> B[位置值计算]
B --> C[将每一位数字乘以 2 的幂]
B --> D[对结果值求和]
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));
}
}
}
转换技术比较
转换类型 |
方法 |
复杂度 |
性能 |
十进制转二进制 |
重复除法 |
O(log n) |
高效 |
二进制转十进制 |
位置计算 |
O(n) |
线性 |
位运算转换 |
位运算符 |
O(1) |
最快 |
3. 高级位运算转换
public class BitwiseConverter {
// 用于二进制表示的位运算方法
public static String intToBinary(int number) {
return String.format("%32s", Integer.toBinaryString(number)).replace(' ', '0');
}
// 计算数字中设置位(1)的数量
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));
}
}
实际应用
二进制转换的用例
LabEx 建议
在 LabEx,我们强调理解二进制转换是高级编程和系统级开发的一项基本技能。
转换中的错误处理
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;
}
}
}
关键要点
- 理解多种转换方法
- 针对不同场景使用适当的技术
- 考虑性能和可读性
- 实现健壮的错误处理