试图在Java中将二进制文件转换为拒绝文件,但我不确定发生了什么,我感觉到它在我的循环中,任何帮助将不胜感激!如果您想查看伪代码,我正在关注它!
System.out.println("Enter a binary number");
Scanner sc = new Scanner(System.in);
String binaryString = sc.next();
int binaryLength = binaryString.length();
int multiplier = 1;
int denaryValue = 0;
for(int n = binaryLength; n >= 1; n--){
int digit = n;
denaryValue = denaryValue + digit * multiplier;
multiplier = multiplier * 2;
}
System.out.println("The denary equivalent is " + denaryValue);
最佳答案
绝对最简单的方法是使用Integer.parseInt(String, 2);
(在您的情况下为Integer.parseInt(binaryString, 2);
)。
但是,如果您确实要运行循环:
for(int n = binaryLength; n >= 1; n--){
int digit = binaryString.charAt(n - 1) - '0';
denaryValue = denaryValue + digit * multiplier;
multiplier = multiplier * 2;
}
就个人而言,如果我真的想重新发明轮子,我会这样做:
if (!binaryString.matches("[01]+")) {
//here we know that there is a character that is not a 0 or a 1
//or that the string is empty
}
for(char c : binaryString.toCharArray()) {
denaryValue += c - '0';
denaryValue <<= 1; //binary left shift; multiply by 2
}
denaryValue >>= 1; //binary right shift; divide by 2