319

I have a number and I want to print it in binary. I don't want to do it by writing an algorithm.

Is there any built-in function for that in Java?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
akshayxyz
  • 3,423
  • 3
  • 16
  • 11

25 Answers25

487

Assuming you mean "built-in":

int x = 100;
System.out.println(Integer.toBinaryString(x));

See Integer documentation.

(Long has a similar method, BigInteger has an instance method where you can specify the radix.)

Morgan Courbet
  • 772
  • 1
  • 8
  • 18
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
268

Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int, representation)

Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation
Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
Mohasin Ali
  • 3,955
  • 1
  • 20
  • 24
  • test it with different numbers, negative, positive, big, small – Tertium Jun 30 '15 at 13:58
  • 16
    `toBinaryString` uses two's complement output, `toString` coverts the number the specified base and puts a negative sign in front, so `toString(-8, 2) == "-1000"` – Joe Jan 10 '16 at 20:22
  • Agreed, surprising Integer.toString(,,) is (still) wrong! Formatter uses Long.toBinaryString() for %x and %X. Annoyingly, you can't append directly to a StringBuilder unless you extract the code from Integer/Long and adapt it to do so; not hard. – Infernoz Nov 11 '22 at 16:22
70
System.out.println(Integer.toBinaryString(343));
Ravi
  • 30,829
  • 42
  • 119
  • 173
adarshr
  • 61,315
  • 23
  • 138
  • 167
24

I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

So here's what I wrote:

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

Invoke it like this:

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}
Maghoumi
  • 3,295
  • 3
  • 33
  • 49
  • Why `result.replace(result.length() - 1, result.length(), "");` is required? As we're passing `int` which is already 32-bit. What we are replacing on the second last line? – Parth Nov 02 '15 at 13:24
  • 2
    @Parth At each step we are appending a space character (" ") to the end of the string. The line you mentioned will get rid of the last appended space character. Essentially, you could call the `String` class's `trim` function to achieve the same effect. – Maghoumi Nov 02 '15 at 14:39
  • You can do this a lot more simply and efficiently by adding 0x100000000 to the number, converting it as a long, and then discarding the leading 1. – user207421 May 12 '16 at 00:16
  • 1
    Another option is to add additional check to the condition: `if (i % groupSize == 0 && i != 0)` – Ilya Serbis Oct 21 '21 at 20:02
  • @user207421 Integer.toUnsignedLong() looks like it is the right answer, but doesn't seem to give the right answer. Formatter uses this logic: `long v = value; if (value < 0) v += (1L << 32);` – Infernoz Nov 11 '22 at 16:35
11
public static void main(String[] args) 
{
    int i = 13;
    short s = 13;
    byte b = 13;

    System.out.println("i: " + String.format("%32s", 
            Integer.toBinaryString(i)).replaceAll(" ", "0"));

    System.out.println("s: " + String.format("%16s", 
            Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));

    System.out.println("b: " + String.format("%8s", 
            Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));

}

Output:

i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101
Seyit Bilal
  • 191
  • 2
  • 16
  • Astonishingly, Formatter doesn't provide boolean formatting conversion! As I discovered while optimising the Formatter code into a separate, optimised, compiled form, which pre-compiled takes 1/5 to 1/3 of the time to execute; why Sun and Oracle didn't do this is also astonishing, given how useful printf-like formatting is! – Infernoz Nov 11 '22 at 16:50
7

Old school:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

Output (least significant bit is on 0 position):

0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0
Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
David Williams
  • 8,388
  • 23
  • 83
  • 171
7

This is the simplest way of printing the internal binary representation of an integer. For Example: If we take n as 17 then the output will be: 0000 0000 0000 0000 0000 0000 0001 0001

void bitPattern(int n) {

        int mask = 1 << 31;
        int count = 0;
        while(mask != 0) {
            if(count%4 == 0)
                System.out.print(" ");

            if((mask&n) == 0) 

                System.out.print("0");



            else 
                System.out.print("1");


            count++;
            mask = mask >>> 1;


    }
    System.out.println();
}
Community
  • 1
  • 1
rpg
  • 141
  • 1
  • 5
6

check out this logic can convert a number to any base

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
        }
    }
    for (int j = binary.length() - 1; j >= 0; j--) {
        System.out.print(binary.charAt(j));
    }
}

OR

StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
    if((n&1)==1){
        binary.append(1);
    }else
        binary.append(0);
    n>>=1;
}
System.out.println(binary.reverse());
Zahid Ali
  • 456
  • 6
  • 20
  • 1
    for input as 0, ` if(a==0){ binary.append(0); System.out.println(binary.toString()); return; }` we need to add this line in second solution above while loop. – Imran Oct 29 '16 at 07:54
3

Simple and pretty easiest solution.

public static String intToBinaryString(int integer, int numberOfBits) {

    if (numberOfBits > 0) {     // To prevent FormatFlagsConversionMismatchException.

        String nBits = String.format("%" + numberOfBits + "s",      // Int to bits conversion
                Integer.toBinaryString(integer))
                .replaceAll(" ","0"); 

        return nBits;   // returning the Bits for the given int.
    }

    return null;        // if the numberOfBits is not greater than 0, returning null.
}
Jack Reez
  • 31
  • 3
  • 2
    I can understand the conversion, but please don't use `return null`. Just throw an `IllegalArgumentException` using a guard statement. Returning `null` on any error is a terrible construction and just passes the buck to the caller. – Maarten Bodewes Aug 09 '21 at 01:29
2

Simply try it. If the scope is only printing the binary values of the given integer value. It can be positive or negative.

      public static void printBinaryNumbers(int n) {
        char[] arr = Integer.toBinaryString(n).toCharArray();
        StringBuilder sb = new StringBuilder();
        for (Character c : arr) {
          sb.append(c);
        }
        System.out.println(sb);
      }

input

5

Output

101

Ganesa Vijayakumar
  • 2,422
  • 5
  • 28
  • 41
2

Solution using 32 bit display mask,

public static String toBinaryString(int n){

    StringBuilder res=new StringBuilder();
    //res= Integer.toBinaryString(n); or
    int displayMask=1<<31;
    for (int i=1;i<=32;i++){
        res.append((n & displayMask)==0?'0':'1');
        n=n<<1;
        if (i%8==0) res.append(' ');
    }

    return res.toString();
}


 System.out.println(BitUtil.toBinaryString(30));


O/P:
00000000 00000000 00000000 00011110 
dhanu10896
  • 315
  • 2
  • 16
1

There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based → modulo/divide/add):

        int decimalOrBinary = 345;
        StringBuilder builder = new StringBuilder();

        do {
            builder.append(decimalOrBinary % 2);
            decimalOrBinary = decimalOrBinary / 2;
        } while (decimalOrBinary > 0);

        System.out.println(builder.reverse().toString()); //prints 101011001
1

Binary representation of given int x with left padded zeros:

org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')
ankitkpd
  • 663
  • 5
  • 19
1

You can use bit mask (1<< k) and do AND operation with number! 1 << k has one bit at k position!

private void printBits(int x) {
    for(int i = 31; i >= 0; i--) {
        if((x & (1 << i)) != 0){
            System.out.print(1);
        }else {
            System.out.print(0);
        }
    }
    System.out.println();
}
parveen
  • 11
  • 1
0

The question is tricky in java (and probably also in other language).

A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.

So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).

The safe way is to use Integer.toString(X,2); this will generate something less elegant:

-11110100110

But it works!!!

ninja
  • 337
  • 3
  • 2
0

I think it's the simplest algorithm so far (for those who don't want to use built-in functions):

public static String convertNumber(int a)  { 
              StringBuilder sb=new StringBuilder();
              sb.append(a & 1);
              while ((a>>=1) != 0)  { 
                  sb.append(a & 1);
               }
              sb.append("b0");
              return sb.reverse().toString();
  }

Example:

convertNumber(1) --> "0b1"

convertNumber(5) --> "0b101"

convertNumber(117) --> "0b1110101"

How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).

parsecer
  • 4,758
  • 13
  • 71
  • 140
0
    for(int i = 1; i <= 256; i++)
    {
        System.out.print(i + " "); //show integer
        System.out.println(Integer.toBinaryString(i) + " "); //show binary
        System.out.print(Integer.toOctalString(i) + " "); //show octal
        System.out.print(Integer.toHexString(i) + " "); //show hex

    }
plowboy
  • 9
  • 1
  • 3
    Thanks a lot for the answer, however please add more description and/or information and how it solves the asked problem so others can easily understand it without asking for clarification :) – koceeng Feb 24 '17 at 04:21
0

Try this way:

public class Bin {
  public static void main(String[] args) {
    System.out.println(toBinary(0x94, 8));
  }

  public static String toBinary(int a, int bits) {
    if (--bits > 0)
        return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
    else 
        return (a&0x1)==0?"0":"1";
  }

}

10010100

pengguang001
  • 4,045
  • 6
  • 27
  • 31
0

Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number. Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}
scopchanov
  • 7,966
  • 10
  • 40
  • 68
0

Since no answer is accepted, maybe your question was about how to store an integer in an binary-file. java.io.DataOutputStream might be what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();
0

Integer.toString(value,numbersystem) --- syntax to be used and pass value

Integer.toString(100,8) // prints 144 --octal

Integer.toString(100,2) // prints 1100100 --binary

Integer.toString(100,16) //prints 64 --Hex

  • Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it answers the specific question being asked. See [answer]. This is particularly important when answering old questions (this one is nearly 10.5 years old) with existing answers (there are already 23 others). – ChrisGPT was on strike Aug 30 '21 at 00:37
  • this answer is a partial copy of an already existing answer! – Ilya Serbis Oct 21 '21 at 19:43
0

This is my way to format an output of the Integer.toBinaryString method:

public String toBinaryString(int number, int groupSize) {
    String binary = Integer.toBinaryString(number);

    StringBuilder result = new StringBuilder(binary);
    for (int i = 1; i < binary.length(); i++) {
        if (i % groupSize == 0) {
            result.insert(binary.length() - i, " ");
        }
    }
    return result.toString();
}

The result for the toBinaryString(0xABFABF, 8) is "10101011 11111010 10111111"
and for the toBinaryString(0xABFABF, 4) is "1010 1011 1111 1010 1011 1111"

Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
0

here is the simplest way you can convert you integer to Binary

System.out.println(Integer.toBinaryString(111));

Ankit Rege
  • 11
  • 4
-2

It works with signed and unsigned values used powerful bit manipulation and generates the first zeroes on the left.

public static String representDigits(int num) {

        int checkBit = 1 << (Integer.SIZE * 8 - 2 );    // avoid the first digit        
        StringBuffer sb = new StringBuffer();

        if (num < 0 ) {     // checking the first digit
            sb.append("1");
        } else {
            sb.append("0");
        }

        while(checkBit != 0) {          
            if ((num & checkBit) == checkBit){
                sb.append("1");
            } else {
                sb.append("0");
            }           
            checkBit >>= 1;     
        }       

        return sb.toString();
    }
-2

` long k=272214023L;

String long = String.format("%64s",Long.toBinaryString(k)).replace(' ','0');

String long1 = String.format("%64s",Long.toBinaryString(k)).replace(' ','0').replaceAll("(\d{8})","$1 "); ` print : 0000000000000000000000000000000000000000000

00000000 00000000 00000000 00000000 0000000

Vasya
  • 1
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '22 at 18:32