二进制Denary转换器在Java中 [英] Binary to Denary Converter in Java

查看:195
本文介绍了二进制Denary转换器在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

努力使二进制转换器在Java中denary,但我不知道怎么回事错了,我有一种感觉,我的循环,任何帮助将是非常美联社preciated!我下面的伪code,如果你想看到它!

 的System.out.println(输入一个二进制数);扫描仪SC =新的扫描仪(System.in);
串binaryString = sc.next();INT binaryLength = binaryString.length();INT乘数= 1;
INT denaryValue = 0;对于(INT N = binaryLength; N> = 1; N - ){
    INT位= N;
    denaryValue = denaryValue +数字*乘数;
    乘数=乘数* 2;
}
的System.out.println(该denary等效为+ denaryValue);


解决方案

绝对最简单的方法是用的Integer.parseInt(字符串,2); (你的情况: 的Integer.parseInt(binaryString,2);

不过,如果你真的想运行循环:

 的for(int N = binaryLength; N> = 1; N  - ){
    INT位= binaryString.charAt(N - 1) - '0';
    denaryValue = denaryValue +数字*乘数;
    乘数=乘数* 2;
}

就个人而言,我会做到这一点,如果我真的想重新发明轮子:

 如果(!binaryString.matches([01] +)){
    //这里我们知道,有一个人物不是0或1
    //或者字符串为空
}
对于(字符C:binaryString.toCharArray()){
    denaryValue + = C - '0';
    denaryValue&所述;&下; = 1; //二进制左移;乘以2
}
denaryValue>> = 1; //二进制右移;除以2

trying to make a converter of binary to denary in java, but I'm not sure whats going wrong, I have a feeling its in my loop, any help would be much appreciated! I am following pseudo code if you would like to see it!

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);

解决方案

The absolute easiest way is with Integer.parseInt(String, 2); (in your case: Integer.parseInt(binaryString, 2);).

However, if you really want to run the loop:

for(int n = binaryLength; n >= 1; n--){
    int digit = binaryString.charAt(n - 1) - '0';
    denaryValue = denaryValue + digit * multiplier;
    multiplier = multiplier * 2;
}

Personally, I'd do this if I really wanted to reinvent the wheel:

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

这篇关于二进制Denary转换器在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆