[java] Converting an int to a binary string representation in Java?

What would be the best way (ideally, simplest) to convert an int to a binary string representation in Java?

For example, say the int is 156. The binary string representation of this would be "10011100".

This question is related to java string binary int

The answer is


here is my methods, it is a little bit convince that number of bytes fixed

private void printByte(int value) {
String currentBinary = Integer.toBinaryString(256 + value);
System.out.println(currentBinary.substring(currentBinary.length() - 8));
}

public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
  if(numbers[i]=='1')
    result += Math.pow(2, (numbers.length-i - 1));
return result;
}

Using bit shift is a little quicker...

public static String convertDecimalToBinary(int N) {

    StringBuilder binary = new StringBuilder(32);

    while (N > 0 ) {
        binary.append( N % 2 );
        N >>= 1;
     }

    return binary.reverse().toString();

}

public class Main  {

   public static String toBinary(int n, int l ) throws Exception {
       double pow =  Math.pow(2, l);
       StringBuilder binary = new StringBuilder();
        if ( pow < n ) {
            throw new Exception("The length must be big from number ");
        }
       int shift = l- 1;
       for (; shift >= 0 ; shift--) {
           int bit = (n >> shift) & 1;
           if (bit == 1) {
               binary.append("1");
           } else {
               binary.append("0");
           }
       }
       return binary.toString();
   }

    public static void main(String[] args) throws Exception {
        System.out.println(" binary = " + toBinary(7, 4));
        System.out.println(" binary = " + Integer.toString(7,2));
    }
}

This should be quite simple with something like this :

public static String toBinary(int number){
    StringBuilder sb = new StringBuilder();

    if(number == 0)
        return "0";
    while(number>=1){
        sb.append(number%2);
        number = number / 2;
    }

    return sb.reverse().toString();

}

public class BinaryConverter {

    public static String binaryConverter(int number) {
        String binary = "";
        if (number == 1){
            binary = "1";
            System.out.print(binary);
            return binary;
        }
        if (number == 0){
            binary = "0";
            System.out.print(binary);
            return binary;
        }
        if (number > 1) {
            String i = Integer.toString(number % 2);

            binary = binary + i;
            binaryConverter(number/2);
        }
        System.out.print(binary);
        return binary;
    }
}

The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.

@Test
public void shouldPrintBinary() {
    StringBuilder sb = new StringBuilder();
    convert(1234, sb);
}

private void convert(int n, StringBuilder sb) {

    if (n > 0) {
        sb.append(n % 2);
        convert(n >> 1, sb);
    } else {
        System.out.println(sb.reverse().toString());
    }
}

There is also the java.lang.Integer.toString(int i, int base) method, which would be more appropriate if your code might one day handle bases other than 2 (binary). Keep in mind that this method only gives you an unsigned representation of the integer i, and if it is negative, it will tack on a negative sign at the front. It won't use two's complement.


This is something I wrote a few minutes ago just messing around. Hope it helps!

public class Main {

public static void main(String[] args) {

    ArrayList<Integer> powers = new ArrayList<Integer>();
    ArrayList<Integer> binaryStore = new ArrayList<Integer>();

    powers.add(128);
    powers.add(64);
    powers.add(32);
    powers.add(16);
    powers.add(8);
    powers.add(4);
    powers.add(2);
    powers.add(1);

    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
    int input = sc.nextInt();
    int printableInput = input;

    for (int i : powers) {
        if (input < i) {
            binaryStore.add(0);     
        } else {
            input = input - i;
            binaryStore.add(1);             
        }           
    }

    String newString= binaryStore.toString();
    String finalOutput = newString.replace("[", "")
            .replace(" ", "")
            .replace("]", "")
            .replace(",", "");

    System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
    sc.close();
}   

}


Using built-in function:

String binaryNum = Integer.toBinaryString(int num);

If you don't want to use the built-in function for converting int to binary then you can also do this:

import java.util.*;
public class IntToBinary {
    public static void main(String[] args) {
        Scanner d = new Scanner(System.in);
        int n;
        n = d.nextInt();
        StringBuilder sb = new StringBuilder();
        while(n > 0){
        int r = n%2;
        sb.append(r);
        n = n/2;
        }
        System.out.println(sb.reverse());        
    }
}

public static string intToBinary(int n)
{
    String s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}

You can use while loop as well to convert an int to binary. Like this,

import java.util.Scanner;

public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the a number : ");
      num = sc.nextInt();
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}

Source and reference - convert int to binary in java example.


Convert Integer to Binary:

import java.util.Scanner;

public class IntegerToBinary {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter Integer: ");
        String integerString =input.nextLine();

        System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
    }

}

Output:

Enter Integer:

10

Binary Number: 1010


This can be expressed in pseudocode as:

while(n > 0):
    remainder = n%2;
    n = n/2;
    Insert remainder to front of a list or push onto a stack

Print list or stack

One more way- By using java.lang.Integer you can get string representation of the first argument i in the radix (Octal - 8, Hex - 16, Binary - 2) specified by the second argument.

 Integer.toString(i, radix)

Example_

private void getStrtingRadix() {
        // TODO Auto-generated method stub
         /* returns the string representation of the 
          unsigned integer in concern radix*/
         System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
         System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
         System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
         System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
    }

OutPut_

Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64

You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:

// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
  final char[] buf = new char[32];
  for (int i = 31; i >= 0; i--) {
    buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
  }
  return new String(buf);
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to binary

Difference between opening a file in binary vs text Remove 'b' character do in front of a string literal in Python 3 Save and retrieve image (binary) from SQL Server using Entity Framework 6 bad operand types for binary operator "&" java C++ - Decimal to binary converting Converting binary to decimal integer output How to convert string to binary? How to convert 'binary string' to normal string in Python3? Read and write to binary files in C? Convert to binary and keep leading zeros in Python

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift