In: Computer Science
3. Write a java method that accepts a binary number
and converts it to decimal then display
the result. For Example:
(110)2 = (6)10
(2
2 *1)+ (21 *1) + (20*0) = 6
Additional task: write a method that accepts a decimal and converts
it to binary.
i need to solve it as soon as
and i will upvote you directly
Binary to Decimal Method:
// function to convert binary to decimal
static int binaryToDecimal(String bin)
{
String num = bin;
int dec = 0, base = 1, len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num.charAt(i) == '1')
dec += base;
base = base * 2;
}
return dec;
}
Decimal to binary Method:
// function to convert decimal to binary
static int decimalToBinary(int dec)
{
int bin = 0, cnt = 0;
while (dec != 0)
{
int rem = dec % 2;
double c = Math.pow(10, cnt);
bin += rem * c;
dec /= 2;
cnt++;
}
return bin;
}
Testing above methods:
Code:
public class Main
{
// function to convert binary to decimal
static int binaryToDecimal(String bin)
{
String num = bin;
int dec = 0, base = 1, len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num.charAt(i) == '1')
dec += base;
base = base * 2;
}
return dec;
}
// function to convert decimal to binary
static int decimalToBinary(int dec)
{
int bin = 0, cnt = 0;
while (dec != 0)
{
int rem = dec % 2;
double c = Math.pow(10, cnt);
bin += rem * c;
dec /= 2;
cnt++;
}
return bin;
}
public static void main(String[] args) {
System.out.println("Decimal Eqivalent of 110 = " + binaryToDecimal("110"));
System.out.println("Binary Eqivalent of 6 = " + decimalToBinary(6));
}
}

Output:

i hope it helps..
If you have any doubts please comment and please don't dislike.
PLEASE GIVE ME A LIKE. ITS VERY IMPORTANT FOR ME