Decimal-Binary Conversion
Ways to Convert Decimal to Binary
Binary Timeline
Division Method
Algorithm for decimal to binary (Not Optimised)
Take input from user
loop until num > 0
rem = num %2
num = num /2
res = rem + res
end loop
print res
String res ="" ;
while (num >0 ){
int rem = num % 2 ;
num = num /2 ;
res = rem +res ;
}
System .out .println ("Binary of the number is: " +res );
Optimised Conversion at Bit Level
Take the last bit with AND Operator(&1)
Prepend to the result
Right Shift by 1 (>>)
Do it till number become 0
Take the last digit (%10)
if last digit is 1
add 2^index in the result
Do it till number become 0
public class convertor {
static void toBinary (int decimal ) {
String result = "" ;
while (decimal > 0 ) {
int lastbit = decimal & 1 ;
result = lastbit + result ;
decimal = decimal >> 1 ;
}
System .out .println (result );
}
static void toDecimal (int binary ){
int result =0 ;
int index =0 ;
while (binary >0 ){
int lastdigit = binary %10 ;
if (lastdigit == 1 ){
result = result + (int ) Math .pow (2 ,index );
}
index ++;
binary = binary /10 ;
}
System .out .println (result );
}
public static void main (String args []) {
toBinary (12 );
toDecimal (1100 );
}
}