Skip to content

Instantly share code, notes, and snippets.

@eienf
Created May 15, 2013 08:49
Show Gist options
  • Save eienf/5582537 to your computer and use it in GitHub Desktop.
Save eienf/5582537 to your computer and use it in GitHub Desktop.
Algorithm for convert binary string to decimal integer.
class Decimal {
public static long toLong(String bin) {
long decimal = 0;
for ( int i = 0; i < bin.length(); i++ ) {
if ( bin.substring(i,i+1).equals("1") ) {
decimal <<= 1;
decimal += 1;
} else if ( bin.substring(i,i+1).equals("0") ) {
decimal <<= 1;
} else if ( bin.substring(i,i+1).equals(" ") ) {
;
} else {
break;
}
}
return decimal;
}
public static void main(String args[]) {
String bin = args[0];
long val = toLong(bin);
System.out.println(bin + " : " + val);
System.out.println("Integer : " + Integer.parseInt(bin,2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment