Maths Involved

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;
}
}
 
M

Michael Redlich

Calum said:
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.

Hi Calum:

I assume that back-to-front is right-to-left, yes?

I was just working out your algorithm on paper using n = 10. The
different values of the variable, v, in the while loop are as follows:

8, 4, 2, 1, 0

which correspond to:

2^3, 2^2, 2^1, 2^0

So I assume that the variable, v, represents the exponents for base 2.
If that's the case, then your program does work as intended, it's just
doing it from left-to-right instead of right-to-left.

Whaddya think...make sense?

Mike.
 
R

Roedy Green

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.

get a piece of paper and pretend to be a computer. for each variable
reserve some space on your paper to record it latest value.
 
T

tom fredriksen

James said:
Integer "divide" and "multiply" by 2, are just a rich man's right and
left shift, respectively.

That what I was thinking as well! Why in gods name do it so complex.

Here is an example of how it could be done in a legible way, not to
mention within the normal idiom of such tasks

int marker = 128;
for(int c=0; c<8; c++) {
if( (marker & value) == marker ) {
System.out.print("1");
} else {
System.out.print("0");
}
marker = marker >>> 1;
}

/tom
 
L

Luke Webber

James said:
Integer "divide" and "multiply" by 2, are just a rich man's right and
left shift, respectively.

Hell yes. Even in languages that lack shift operators, it would be
smarter to use v += v than v *= 2. Hopefully the optimiser works that
out, though.

Luke
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top