简体   繁体   中英

Converting an integer to binary using old-school way

I know it's pretty easy to achieve this in Java with System.out.println(Integer.toBinaryString(num));

However, I want to do this using loops, I tried this but the order is reversed. How can I fix this:

public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int num = in.nextInt();

    while (num >= 2) {

      System.out.print(num % 2);

      num = (int) num / 2;
    }

    System.out.println(num);
  }
}

For example;

input num=8

prints 0001 but it must be 1000 instead.

Use a String to store the results:

String binaryString = Integer.toString(num % 2);
while (num >= 2) {
    num = (int) num / 2;
    binaryString = Integer.toString(num % 2) + binaryString;
}
System.out.println(binaryString);

As Brian suggests, stored the intermediate values in a String.

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        String x = "";

        while (num >= 2) {
            x = x + Integer.valueOf(num % 2);

            num = (int) num / 2;
        }

        String newX = new StringBuilder(x).reverse().toString();

        System.out.print(num + newX);
    }
}

If you really want it old- school then you can do it recursively:

public static void main(String[] args) {
    try (Scanner in = new Scanner(System.in)) {
        int num = in.nextInt();
        System.out.println(getBinaryString(num));
    }
}

//Does not take care of negative values
private static String getBinaryString(int num) {
    if (num <= 2) {
        return "" + (num % 2);
    }
    return getBinaryString(num / 2) + (num % 2);
}

Not meant to be taken too seriously the following code is a really old-school implementation which makes use of traditional bit masking and bit shifting. It also works for negative numbers and thus produces the same results as Integer.toBinaryString() . By making the intermediate char array static thread-safety is traded for performance, so be sure not to use it in a multi-threaded environment. Of course we're going to use the same constant values in various places, meaningless identifiers and other ways of obfuscation optimiziation to make sure that lamers don't immediately understand what's going on beginners see how good code should look like. Remember: Shorter code = better code and smaller file = less transmission time so omit useless whitespace and line breaks where possible. Don't exceed 80 chars per line so your matrix printer will happily print out your code on listing paper without any hassle.

private static char[]a=new char[32];
public static String b(int c) {
    int d=32; do a[--d]=(char)(48+(c&1)); while ((c>>>=1)!=0);
    return new String(a,d,32-d);
}

Conclusion: Be glad that things like Integer.toBinaryString() are there and ready to be used in production code.

You can calculate the number of bits ahead of time and print the bits in reverse.

This will work for any given base (2 - 9).

import java.util.Scanner;

public class Main {
    public static final int BASE = 2;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: "); // Promp user

        int num = in.nextInt();
        int bits = (int) Math.floor(Math.log(num) / Math.log(BASE)); // Calculate min bits

        for (int bit = bits; bit >= 1; bit--) { // Loop in reverse
            int factor = (int) Math.pow(BASE, bit);
            System.out.print(num / factor);
            num = (int) num % factor;
        }

        System.out.println(num);
        in.close();
    }
}

Support for any base/alphabet.

import java.util.Scanner;

public class Main {
    public static final int BASE = 16;
    public static final char[] ALPHABET = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");

        int num = in.nextInt();
        int bits = (int) Math.floor(Math.log(num) / Math.log(BASE)) + 1;

        if (bits <= 0) {
            System.out.println(0);
        }

        for (int bit = bits - 1; bit >= 0; bit--) {
            int factor = (int) Math.pow(BASE, bit);
            System.out.print(ALPHABET[num / factor]);
            num = (int) num % factor;
        }

        in.close();
    }
}

Here is Viktor's suggested recursive implementation with custom base support.

import java.util.Scanner;

public class Main {
    public static final int BASE = 16;
    public static final char[] ALPHABET = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: "); // Prompt user
        System.out.println(integerToString(in.nextInt()));
        in.close();
    }

    public static String integerToString(int n) {
        return integerToString(n, BASE);
    }

    public static String integerToString(int n, int radix) {
        return integerToString(n, radix, ALPHABET);
    }

    public static String integerToString(int n, int radix, char[] alphabet) {
        return (n > radix ? integerToString(n / radix, radix, alphabet) : "") + ALPHABET[n % radix];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM