简体   繁体   English

java中二进制到十进制转换的问题(数组)

[英]Problems with Binary to Decimal conversion in java (arrays)

My assignment is to convert binary to decimal in a JLabel array without using pre-written methods (there's no user input).我的任务是在不使用预先编写的方法(没有用户输入)的情况下将 JLabel 数组中的二进制转换为十进制。 I have the right idea but for some reason the output is always a little bit off.我有正确的想法,但由于某种原因,输出总是有点偏离。 I've gone through it countless times but I can't find anything wrong with my algorithm and I'm very confused as to why it doesn't produce the correct answer.我已经经历了无数次,但我找不到我的算法有什么问题,我很困惑为什么它没有产生正确的答案。 I'd be very grateful if someone could help me out.如果有人可以帮助我,我将不胜感激。 Thanks!谢谢!

Side note: I've read similar discussion threads regarding binary to decimal conversions but I don't understand how to do it with arrays.旁注:我已经阅读了有关二进制到十进制转换的类似讨论线程,但我不明白如何使用数组进行转换。

Here is a snippet of my code:这是我的代码片段:

   private void convert()
   {
    int[] digit = new int[8]; //temporary storage array
    int count = 0;
    for(int x = 0; x < digit.length; x++)
     {
     digit[x] = Integer.parseInt(bits[x].getText()); //bits is the original array
     count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x)); 
    }
     label.setText("" + count); 
   }

You are following the binary number from left to right but are grabbing the wrong digit.您从左到右跟踪二进制数,但抓取了错误的数字。 You want the same digit but to multiply by the right power of two - first index being +n*128 and not +n*1您想要相同的数字,但要乘以 2 的右幂 - 第一个索引是 +n*128 而不是 +n*1

int count = 0;
for(int i = 0; i < bits.length; i++) {
    count += Integer.parseInt(bits[i].getText()) * Math.pow(2, bits.length - i - 1);
}

Obviously there is a bug in your snippet.显然,您的代码段中存在错误。

You set the digit[x], but not set the digit[length - 1 - x].您设置了数字 [x],但未设置数字 [长度 - 1 - x]。

for example, x = 0, you set the digit[0], but not set digit[7].例如,x = 0,您设置了 digit[0],但未设置 digit[7]。
So there will be an error when you want use the digit[length - 1 -x] here :因此,当您要在此处使用 digit[length - 1 -x] 时会出现错误:

count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x));

This the correct code here:这是这里的正确代码:

private void convert()
{
    int count = 0, length = 8;
    for(int i = 0; i < length; count += Integer.parseInt(bits[i].getText()) * (1 << (length - 1 - i)), i++);
    label.setText("" + count); 
}

Have not test the code.没有测试代码。 But I think it will work.但我认为它会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM