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

• 10-04-2011, 04:45 AM
Reads a number and prints it's binary digits, need help :)
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.
• 10-04-2011, 06:31 PM
eRaaaa
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;
• 10-04-2011, 06:39 PM
Iron Lion
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:
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; }```