Question 60 : Write a program in Java to input a number from the user and convert it into binary notation.
Java Program :
class binary
{
static void cal(int n)
{
int a,k=n;
String s="";
while(n>0)
{
a=n%2==0?0:1;
s=String.valueOf(a)+s;
n/=2;
}
System.out.print(k+" --> "+s);
}
}
Java Program :
class binary
{
static void cal(int n)
{
int a,k=n;
String s="";
while(n>0)
{
a=n%2==0?0:1;
s=String.valueOf(a)+s;
n/=2;
}
System.out.print(k+" --> "+s);
}
}
public static String convertToBinary(int x) {
ReplyDeletechar[] bits = new char[32];
int i = bits.length;
while (x != 0) {
//Storing the last bit value to the array from the end
bits[--i] = (x % 2 ) == 1 ? '1' : '0';
System.out.println("bits["+i+"] ::"+bits[i]);
System.out.println("x::"+x+" x%2 ::"+ (x%2));
//Moving the binary towards right nothing but divide by 2
//x >>= 1;
x/=2;
System.out.println("x/2::"+x);
}
public static String convert(int x) {
ReplyDeletechar[] bits = new char[32];
int i = bits.length;
while (x != 0) {
//Storing the last bit value to the array from the end
bits[--i] = (x & 1) == 1 ? '1' : '0';
System.out.println("bits["+i+"] ::"+bits[i]);
System.out.println("x::"+x+" x&1 ::"+ (x&1));
//Moving the binary towards right nothing but divide by 2
x >>= 1;
System.out.println("x>>1::"+x);
}