To binary number

+1 Arnab Banerjee · January 24, 2015
How to convert any number to its corresponding binary number using Java ?

Post a Reply

Replies

Oldest  Newest  Rating
0 Siddharth Venu · March 10, 2016

import java.lang.StringBuilder;
import java.lang.Integer;

public class DeciToBinary {

public static int toBinary(int n){
int temp;
int ans;
StringBuilder builder=new StringBuilder();
for(temp=n;temp!=1;){
int remainder=temp%2;
builder.append(remainder);
temp/=2;
}
builder.append(1);
builder.reverse();
String binary=builder.toString();
ans=Integer.parseInt(binary);
return ans;
}

public static void main(String[] args) {
System.out.println(toBinary(21));
System.out.println(toBinary(121));
               System.out.println(toBinary(827));
}
}


Tested, working fine.
http://pad2.whstatic.com/images/thumb/1/1f/Convert-from-Decimal-to-Binary-Step-4-Version-2.jpg/aid5981-900px-Convert-from-Decimal-to-Binary-Step-4-Version-2.jpg 
I used this method for the conversion. <a href="http://www.wikihow.com/Convert-from-Decimal-to-Binary">Source</a>
0 Gary Whitney · March 11, 2016
All numbers integers are binary. There just isn't a binary data type in Java.
Run this code to see how Integer.toBinary() works.

        int binAND, binOR, binXOR;
        String strBin3, strBin7, strBinAND, strBinOR,strBinXOR;
        strBin3 =(Integer.toBinaryString(3));
        strBin7 =(Integer.toBinaryString(7));
        binAND = 3 & 7;
        binOR = 3 | 7;
        binXOR = 3 ^ 7;
        strBinAND = (Integer.toBinaryString(binAND));
        strBinOR = (Integer.toBinaryString(binOR));
        strBinXOR = (Integer.toBinaryString(binXOR));
        System.out.printf("bin3 = %s and bin7 = %s.\n",strBin3, strBin7);
        System.out.println("strBinAND = "  + strBinAND);
        System.out.println("strBinOR = "  + strBinOR);
        System.out.println("strBinXOR = "  + strBinXOR);
  • 1

Java / Android Development

107,314 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator