1

Main:

public class Main{                                      
  public static void main(String[] args){                                       
    System.out.println(Convert.BtoI("101101010101"));                                   
    System.out.println(Convert.BtoI("1011110"));                                                                            
  }                                     
}

Sub:

public class Convert{                                       
  public static int BtoI(String value){                                     
    int no = 0;                                                                         

    for(int i=value.length()-1;i>=0;i--){                                       
      if(value.charAt(i)=='1')                                      
        no += (???) ;                                       
      ++;                                       
    }                                       
    return no;                                      
  }                                     
}

How can I convert a string binary to integer without using maths.pow, just using + - * and /, should I implement another for loop for it is int j = 1;i <= example; i*=2){ ?. I am quite confused and want to learn without the usage of maths.pow or any similar codes.

6
  • stackoverflow.com/a/10179141/4267015 duplicate her is your answer Commented Dec 17, 2018 at 23:12
  • In Java x << y is effectively equivalent to Math.pow(2, y). Commented Dec 17, 2018 at 23:18
  • 1
    Duplicate is correct, however I don't like the accepted answer because sometimes the goal is to re-invent the wheel and not use a built-in routine like Integer.parse(). The secret is to at each step multiply by the radix. For base 10 you multiply by 10, and for base 2 you multiply by two. Note in the duplicate link at least two answer shift by 1 at each iteration, which is the same as multiplying by 2. Commented Dec 17, 2018 at 23:18
  • You could simply implement your own pow method. Commented Dec 17, 2018 at 23:51
  • @Jean-ClaudeArbaut how do you want to binary shift string? Commented Dec 17, 2018 at 23:52

3 Answers 3

2

From the beginning of the string until to the end you can just multiply each character with its power and sum up the total which gives you the base ten value:

public static int binaryToInt(String binaryNum) {
    int pow = 1;
    int total = 0;

    for (int i = binaryNum.length(); i > 0; i--) {
        if (binaryNum.charAt(i-1) == '1')  {
            total += pow;
        }
        pow *= 2;
    }

    return total;
}

But i think this is way more elegant:

String binaryNum = "1001";
int decimalValue = Integer.parseInt(binaryNum, 2);
Sign up to request clarification or add additional context in comments.

Comments

1

How about Integer.parseInt(yourString,2); ?? 2 means you are parsing base2 number.

4 Comments

This isn't wrong, but I'm pretty sure the OP's goal is to understand how Integer.parse() works, so they want to re-implement it themselves.
Tldr and got focus on the topic as it was clear enough.
He / she explicitly says "just using + - * and /" and loops.
"Shift is likely better than multiplication" - I doubt that, and if it was then the JIT compiler would / should make the same optimization!
0

Starting from your code + some vital style changes:

public class Convert {                                       
    public static int binaryToInt(String value) {                                     
        int no = 0;                                                                         

        for (int i = 0; i < value.length() - 1; i++) {
            no = no * 2;             // or no *= 2;                                  
            if (value.charAt(i) == '1') {                                     
                no = no + 1;         // or no++                                    
            }                                       
        }                                       
        return no;                                      
    }                                     
}

The meaning of the code I added should be self-evident. If not, I would encourage you to work out what it does as an exercise. (If you are not sure, use a pencil and paper to "hand execute" it ...)

The style changes (roughly in order of importance) are:

  1. Don't start a method name with an uppercase character.
  2. Use camel-case.
  3. Avoid cute / obscure / unnecessary abbreviations. The next guy reading your code should not have to use a magic decoder ring to understand your method names.
  4. Put spaces around operators.
  5. 4 character indentation.
  6. Put spaces between ) and { and before / after keywords.
  7. Use curly brackets around the "then" and "else" parts of an if statement, even if they are not strictly necessary. (This is to avoid a problem where indentation mistakes cause you to misread the code.)

2 Comments

Assuming the string starts with the MSB, there is a bug (the OP didn't tell, but it's the most common I think). Also, the code is a bit faster (I get 20%) when replacing the if with no |= 1 & value.charAt(i);. But then of course it's not using only +-*/.
1) Corrected. Thanks. 2) "Then of course it's not using only +-*/" - Correct! Furthermore, I do not think it is helpful for a beginner to delve into micro-optimizations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.