以下是程序中的一个小功能:将十进制转换成二进制 ,用操作每一个二进制位实现
但是在测试最小负数的时候有一个异常,求解决
public class StringToDec {
public static void main(String[] args) {
// 用正数进行测试
System.out.println(Integer.toBinaryString(1234567));
System.out.println(DectoBinary(1234567));
System.out.println("---------------------");
// 用负数进行测试
System.out.println(Integer.toBinaryString(-4534543));
System.out.println(DectoBinary(-4534543));
System.out.println("---------------------");
System.out.println(Integer.toBinaryString(Integer.MAX_VALUE));
System.out.println(DectoBinary(Integer.MAX_VALUE));
System.out.println("---------------------");
// 测试最小负数的时候出现问题
System.out.println(Integer.toBinaryString(Integer.MIN_VALUE));
System.out.println(DectoBinary(Integer.MIN_VALUE));
}
// 自定义的将十进制数转成二进制数的方法,正负均可
public static String DectoBinary(int number) {
int remainder;
int[] arr = new int[32];
int pos = arr.length - 1; // 指针
int length = String.valueOf(number).length();
boolean flag = true, flag_1 = false;
StringBuilder sb = new StringBuilder();
// 负数先求得其十进制相反数
if (number < 0) {
flag = false;
number = Integer.parseInt(String.valueOf(number).substring(1));
}
while (number != 0) {
remainder = number % 2;
number = number / 2;
arr[pos--] = remainder;
}
// 对负数求其二进制
if (!flag) {
// 先将每一位变反
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] ^ 1;
}
// 再将变反后的各位加1
for (int i = arr.length - 1; i >= 0; i--) {
if (i == arr.length - 1) {
if (arr[i] == 1) {
flag_1 = true;
} else if (arr[i] == 0) {
arr[i] = 1;
}
}
if (arr[i] == 1 && flag_1) {
arr[i] = 0;
flag_1 = true;
} else if (arr[i] == 0 && flag_1) {
arr[i] = 1;
flag_1 = false;
} else
flag_1 = false;
}
pos = -1;
}
for (int i = pos + 1; i < arr.length; i++) {
sb.append(arr[i]);
}
return sb.toString();
}
}
结果:
100101101011010000111
100101101011010000111
---------------------
11111111101110101100111011110001
11111111101110101100111011110001
---------------------
1111111111111111111111111111111
1111111111111111111111111111111
---------------------
10000000000000000000000000000000
Exception in thread "main" java.lang.NumberFormatException: For input string: "2147483648"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:499)
at java.lang.Integer.parseInt(Integer.java:527)
at com.heimestudy.cn.StringToDec.DectoBinary(StringToDec.java:37)
at com.heimestudy.cn.StringToDec.main(StringToDec.java:21)
|