Convert a Binary string to Integer...
code snippet:
method 1 :-
import java.util.*;
public class BinaryToInt{
public static void main(String nag[]){
Scanner console= new Scanner(System.in);
System.out.println("enter any binary number:");
String binaryString=console.next().trim();
System.out.println("int representation of the given binary is:"+binaryToInt(binaryString));
}
private static int binaryToInt(String numberString){
int result=0;
int numberStringLength=numberString.length();
char[] binaryCharArray=new char[numberStringLength];
for(int i=0;i<numberStringLength;i++){
binaryCharArray[i]=numberString.charAt(i);
}
int[] binaryIntArray=convertBinaryCharArrayToBinaryIntArray(binaryCharArray);
result= calculateBinary(binaryIntArray);
return result;
}
private static int[] convertBinaryCharArrayToBinaryIntArray(char[] charArray){
int arrayLength=charArray.length;
int[] intArray=new int[arrayLength];
for(int i=0;i<arrayLength;i++){
if((int)charArray[i]==48){
intArray[i]=0;
}
if((int)charArray[i]==49){
intArray[i]=1;
}
}
return intArray;
}
private static int calculateBinary(int[] binaryIntArray){
int value=0;
int arrayLength=binaryIntArray.length;
for(int i=0;i<arrayLength;i++){
value=value+binaryIntArray[i]*pow(2,(arrayLength-1)-i);
}
return value;
}
public static int pow(int value, int power){
int v=1;
for(int i=0; i<power;i++){
// System.out.println("loop:"+(i-1));
v=v*value;
}
return v;
}
}//end class
method 2 :-
Use Integer.parseInt(String str, int num); directly
code snippet:
method 1 :-
import java.util.*;
public class BinaryToInt{
public static void main(String nag[]){
Scanner console= new Scanner(System.in);
System.out.println("enter any binary number:");
String binaryString=console.next().trim();
System.out.println("int representation of the given binary is:"+binaryToInt(binaryString));
}
private static int binaryToInt(String numberString){
int result=0;
int numberStringLength=numberString.length();
char[] binaryCharArray=new char[numberStringLength];
for(int i=0;i<numberStringLength;i++){
binaryCharArray[i]=numberString.charAt(i);
}
int[] binaryIntArray=convertBinaryCharArrayToBinaryIntArray(binaryCharArray);
result= calculateBinary(binaryIntArray);
return result;
}
private static int[] convertBinaryCharArrayToBinaryIntArray(char[] charArray){
int arrayLength=charArray.length;
int[] intArray=new int[arrayLength];
for(int i=0;i<arrayLength;i++){
if((int)charArray[i]==48){
intArray[i]=0;
}
if((int)charArray[i]==49){
intArray[i]=1;
}
}
return intArray;
}
private static int calculateBinary(int[] binaryIntArray){
int value=0;
int arrayLength=binaryIntArray.length;
for(int i=0;i<arrayLength;i++){
value=value+binaryIntArray[i]*pow(2,(arrayLength-1)-i);
}
return value;
}
public static int pow(int value, int power){
int v=1;
for(int i=0; i<power;i++){
// System.out.println("loop:"+(i-1));
v=v*value;
}
return v;
}
}//end class
method 2 :-
Use Integer.parseInt(String str, int num); directly
No comments:
Post a Comment