Lil java help for a noob please

Is it? I'm already stuck lol :P

Basically do i have to try and implement using a charAt on each character of the binary string...if the character is 1 then what do i do mathematicaly? I know how to do it mentaly but im not sure how java would do it if you know what i mean?

Thanks
 
Code:
    static int BinToDec(final int[] bin) {
        int dec = 0;
        for (int i = bin.length - 1; i >= 0; i--) {
            dec <<= 1;
            dec += bin[i];
        }
        return dec;
    }
Something like this?
 
Hey guys...with binary to decimal i have the same problem as before, the input is read from right to left instead of left to right therefore the wrong decimal number is calculated. Im stumped with how to change it, here is my code:

Code:
public static int binTodec (String b){
  
    int l = b.length()-1;
    int dec = 0;
    for (int i = l; i >= 0; i--)
    {
      int power = 1;
      for (int p = 1; p <= i; p++)
     {
       power = power * 2;
     }
    if (b.charAt(i) == '1')
    {
      dec = dec + power;
    }
  }
    return dec;
  }
 
Last edited:
Far too confusing

This works...

Code:
public int binTodec (String b)
	{
		int i = b.length()-1;
		int dec = 0;
		int pos = 1;
		for(int j=i;j>-1;j--)
		{
			if(b.charAt(j) == '1')
			{
				dec = dec+pos;
			}
			pos = pos * 2;
		}
		return dec;
	}

Are you at KCL? 1st year?
 
Back
Top Bottom