0

My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.

public static int DecToBin(int num) {
    int binNum = 0;
    int divisor = num;
    int mod = 0;
    int exp =0;

    while(divisor != 0){
        mod = divisor%2;
        divisor = divisor/2;
        if(mod==1){
            binNum = (int) (binNum + (Math.pow(10, exp)));
        }
        exp++;
    }
    return binNum;

}

3
  • 1
    you can't, not this way. you are trying to represent numbers that are too large. You represent 2^10 as a 10^10 number, which is > 2^32. Use a String? Commented Nov 10, 2014 at 23:44
  • My method has to return an int type. I thought int was good upto 2^32. Commented Nov 11, 2014 at 0:02
  • Never mind I've been a fool. You're absolutely correct. I need string. Thank you very much. Commented Nov 11, 2014 at 0:13

2 Answers 2

1

An always easy way to accomplish this is:

Integer.toBinaryString(int);

This is the easiest way to do this but their might be more efficiant ways to do it.

Hopefully this is what you were looking for

Sign up to request clarification or add additional context in comments.

Comments

0

As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.

I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:

String binaryString = "";
int value = 100;
while(value > 0){
   int remainder = value % 2;
   value = value/2;
   binaryString = remainder + binaryString;
}

I tested this in a quick console run and it produced '1100100' which is correct.

EDIT I used this as a reference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.