Problem, write a method for converting numbers from decimal ss to binary ss.

public class Binary { public static void binar(int a) { int i, b; while(a !=0 ) { b = a%2; System.out.print(b); a = a/2; } } public static void main(String [] args) { binar(8); } } 

Question: Why does the number print out in reverse order? Can anyone suggest?

    5 answers 5

    Because try to solve the problem manually and immediately understand everything.

     b = 8 % 2 = 0 b = 4 % 2 = 0 b = 2 % 2 = 0 b = 1 % 2 = 1 

    And you consistently output it accordingly. As a solution to the problem, write everything into a string (StringBuilder), and then flip it.

    • one
      Just write in StringBuilder, and not directly in the string. - yozh
    • It is logical :) Corrected - Dex
    • I did not think about this situation =) thank you for the help;) - Kobayashi_Maru

    khem Maybe so?

     int a = 290; System.out.println(Integer.toString(a, 2)); 

    or so

     public static String toBinaryString(int i) { return toUnsignedString(i, 1); } 
    • The author has just the goal: "to write a method for converting a number from decimal ss to binary ss." Of course, in actual development it is worth using a ready-made solution. - yozh
    • public static String binar (int a) {return Integer.toString (a, 2); } - the condition is met - Anton Feoktistov

    Here is the solution without using String.

      public static void binar(int n) { int i = bitsInNumber(n); int bit; while ( --i >= 0 ){ bit = (n & (1 << i)) == 0 ? 0 : 1; System.out.print(bit); } } public static int bitsInNumber(int n) { int res = 0; while (n > 0) { n >>= 1; res++; } return res; } 

      Is not it easier to first calculate and then withdraw? Or is the task in the output? If in the output, you can immediately hammer in the line in the desired sequence and then output.

      • Here is the task itself: For example, for example, the return will be "1000". - Kobayashi_Maru

      The solution was found =)

       public class Binary { public static void binar(int a){ int b; String temp = ""; while(a !=0){ b = a%2; temp = b + temp; a = a/2; } System.out.print(temp); } public static void main(String [] args) { binar(5); } } 
      • if your task was to output a binary representation of the string in order to "pass the lab", then yes. in all other cases I advise you to pay attention to the answer @ Anton-Feoktistov - jmu
      • The task is translated by the commentary above;) In this case, the goal was to apply the knowledge gained in practice, moreover, the question was somewhat different, not to suggest a solution, but to suggest why a certain action occurs; For the optimal solution provided, of course, thanks! (I will keep it in mind in the future) =) - Kobayashi_Maru