# Thread: Reads a number and prints it's binary digits, need help :)

1. Member
Join Date
Sep 2011
Posts
45
Rep Power
0

## Reads a number and prints it's binary digits, need help :)

Java Code:
```import java.util.Scanner;

//Class definition
public class Bits {
public static void main(String[] args) {
// declare
int n;
int rem;

// User input
Scanner in = new Scanner(System.in);
System.out.println();
n = in.nextInt();

// Calculate
while (n > 0) {
System.out.print(rem = n % 2);
n = n / 2;
}
}
}```
That's what I have so far, but my results are completely reversed from what the problem my professor gave me described.
For example, if the input is 244, you should get 11110100, whereas I get 00101111. Keep in mind I didn't even know how binary worked before this problem so I wouldn't be surprised if my program isn't all that accurate to what I should have. Also, he says my result should be a string not an int. I don't really understand how that works...

Edit, I think my binary is correct. He wants the most significant bits on the left though.
Last edited by Aimforthehead; 10-04-2011 at 04:59 AM.

2. Senior Member
Join Date
Oct 2010
Location
Germany
Posts
787
Rep Power
8

## Re: Reads a number and prints it's binary digits, need help :)

You have to use a StringBuilder with the method insert with the offset of 0 :)
After your loop you can print the builder.toString !
StringBuilder binary = new StringBuilder();
// Calculate
while (n > 0) {
binary.insert(0,rem = n % 2);
n = n / 2;
}
System.out.println(binary);

Or if you dont know the stringbuilder class, use the normal string class
binary = (rem = n % 2) + binary;

3. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
7

## Re: Reads a number and prints it's binary digits, need help :)

When working with bits, it's worth keeping the bitwise operators in mind. Your problem can be solved without them, but situations like these are exactly what they're there for.

To check whether a given bit is set, you can do something like the following:
Java Code:
```final int NUMBER_OF_BITS_INT = 32;
private boolean isBitSet(int num, int bit) {
/* bit must be between 1 and 32 */
return (num & 1 << (NUMBER_OF_BITS_INT - bit)) != 0;
}```
Last edited by Iron Lion; 10-04-2011 at 06:46 PM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•