C
Calum Maciver
I've got an example program that converts positive integers into
binary. I'm having trouble understanding how the maths involved works.
Normally you work out the binary back to front but here it does it the
otherway round. Could someone please explain why this works.
public void printBinary( int n )
{
int v = 1;
while (v <= n/2)
v *= 2;
while ( v > 0 )
{
if (n < v)
System.out.print("0");
else
{
System.out.print("1");
n = n - v;
}
v = v/2;
}
}
binary. I'm having trouble understanding how the maths involved works.
Normally you work out the binary back to front but here it does it the
otherway round. Could someone please explain why this works.
public void printBinary( int n )
{
int v = 1;
while (v <= n/2)
v *= 2;
while ( v > 0 )
{
if (n < v)
System.out.print("0");
else
{
System.out.print("1");
n = n - v;
}
v = v/2;
}
}