Binary to Decimal Calculation in java how i coded it

0
18
• 1
•
•
•
•
•
•
•
•
•
1
Share

Get a detailed description here.

Lets create the logic:

1. Get the binary String.
2. Find out the length.
3. Remember when we read a string from first it is actually the last element of the binary number system.
4. Convert the binary string into Array.
5. We will only take care of the 1s not the zeros. As Zero is actually adding Zero.
6. So we will set a pointer(please don’t worry…this a variable only…not C’s pointer) to initial position and scan through the string.
7. When ever we will get one (1) we will check the position with respect to string starting from last.
8. We will multiply 2 that many number of times i.e. 2 to the power of position.
9. Remember if the last position is 0 it is ok but if it is 1 ..we need to add one.two to the power 0 is one.
Thats it.

Lets code

1. For user input please refer here
2. For length calculaton

int len=input.length();

3. For  rest of the things

public  void binToDec(String input) {
int len=input.length();
//res is the output decimal number
int res=0;
for(int i=0;i<len;i++) {
//consider only those cases where the 1 is present
if (output.charAt(i)==’1′) {
//checking 9th condition
if(i==(len-1))
{
res+= 1;
}
else
{
//power calculation function can be found here
res+= calcpowerof2(2,len-(i+1));
}

}

}
System.out.println(“res—“+res);

}
Don't miss out!

Receive top technical news, lesson ideas, travel tips and more!

Give it a try. You can unsubscribe at any time.