简体   繁体   中英

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

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].

for example, x = 0, you set the digit[0], but not set digit[7].
So there will be an error when you want use the digit[length - 1 -x] here :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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