Converting Decimal to Binary - HELP!

homework

#1

Hey!

i need your help!

For many hours I’m sitting on this code and i can’t find the mistake:

public static int dezimalzahlUmwandelnVorwaerts(int decimalInbinaer) {

	for (int i = 100 ; i >= 0; i--) {

		while (decimalInbinaer >= (int) Math.pow(2, i)) {

			if (decimalInbinaer >= (int) Math.pow(2, i)) {
				System.out.print("1");
			}
			
			else {
			System.out.println("0");
			}
		decimalInbinaer -= Math.pow(2, i);	
		}
	}
	return decimalInbinaer;

}

}

The test number was 1543.

My program always prints out: “11111”

However the right binary number should be: “11000000111”

It seems, that only the if condition is checked. But the else if condition (which prints out the zeros) is ignored.

Can someone help me?

I know how to solve this problem with “%” and dividing. However than the binary number is printed out backwards.

However i want to use the potency method, thus the binary is printed out forward.

Also I’m not allowed to use any other Methods in Java e.g. “Integer.parseInt(value, 2);”

Thank you very much for your help!


#2

Did you mean to write, println?

This is not Java, but Python; however, the algorithms should give some hints.

>>> b = ""
>>> x = 1543
>>> while x > 0:
    b = str(x % 2) + b
    x //= 2

    
>>> b
'11000000111'
>>> 

and,

>>> from math import log
>>> x = 1543
>>> y = 1
>>> while y > 0:
	y = int(log(x, 2))
	print (2 ** y)
	x -= 2 ** y

	
1024
512
4
2
1
>>> 

Here is one more algorithm…

>>> x = 1543
>>> y = int(log(x, 2))
>>> while y >= 0:
	print (1 if x & 2 ** y else 0, end='')
	y -= 1

	
11000000111
>>> 

#3

Thanks a lot!

That helped very much!