-1

I am trying to convert the no n with base b into corresponding value in the decimal no system. This code is giving the wrong output.

For example [1172]base 8 output should be [634] base 10 but it is giving 100 as output.

import java.util.*;     
public class Main{
      
      public static void main(String[] args) {
          Scanner scn = new Scanner(System.in);
          int n = scn.nextInt();
          int b = scn.nextInt();
          int d = getValueIndecimal(n, b);
          System.out.println(d);
       }
      
       public static int getValueIndecimal(int n, int b){
          // write your code here
          int k=0;
          int result = 0;
        
          while(n!=0)
          {
              int r = n % 10;
              b = b^k;
              result += r * b;
              k = k+1;
              n = n / 10;
          }
          return result;
       }
      }
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Rajeev
  • 71
  • 9
  • 5
    While we often write numbers like 2^8 to mean 2 to the power of 8, in java the expression `2^8` is not exponentiation but bitwise exclusive or (and therefore `2^8 == 10`). So the line `b = b^k;` does not give the result that you expect. – Thomas Kläger Sep 11 '21 at 05:51
  • @BoristheSpider many new java programmer may have same doubt who are trying to do Any Base Conversion. please don't downvote, this question may help new programmer. – Rajeev Sep 11 '21 at 08:07
  • Strictly not any base conversion, but any positive base <= 10. I downvoted because it was a poorly asked question, not because of the question. You have now added _an_ example of the incorrect output you are seeing which makes is passable as a question. I have removed by downvote. – Boris the Spider Sep 11 '21 at 11:54

1 Answers1

3

^ isn't an exponent, it's the xor operator.

For an exponent, you can use Math.pow:

b = (int) Math.pow(b, k);

However, note that you don't reset b between iterations, so using pow like that wouldn't be correct either. If you want to keep b between iterations, you just need to continuously multiply it by the same base:

public static int getValueIndecimal (int n, int b) {
    int result = 0;
    int pow = 1;
    
    while(n != 0) {
        int r = n % 10;
        result += r * pow;
        n /= 10;
        pow *= b
    }
    return result;
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Mureinik
  • 297,002
  • 52
  • 306
  • 350