When I am changing from binary to decimal if i give input like 001110 ,,, I am getting output as 40. What to do in this case?

public class AnybaseToDecimal {

public static void main(String[] args) {
	
	System.out.println(anybasetoDecimal(001110,2));
	

}


public static int anybasetoDecimal(int snum , int sb) {
	int ans = 0;
	int mul = 1;
	while(snum>0) {
		int rem = snum%10;
		ans = ans + rem*mul;
		mul = mul*sb;
		snum/=10;
	}
	return ans;
}

}

@LakshmiPrasanna0303,
https://ide.codingblocks.com/s/251057 corrected code

Don’t use int for input. Because 001110 is not an integer. You can use a string. Or if you want to use an integer don’t put any zeros before the number.

I have attached the string implementation in the code.

Your logic was correct

1 Like

Please explain me this line in which you have written–
int rem = (snum.charAt(snum.length() - i - 1) - 48) % 10;

@LakshmiPrasanna0303,
Say if the snum string is 001110. In order to convert from binary to decimal we need to start from the last char. So that will be “snum.charAt(snum.length() - i - 1)”.

So we get the character which is snum.charAt(snum.length() - i - 1). Now we need to convert this to int. So we subtract 48 from it which is the ascii value of ‘0’

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.