Created
May 15, 2013 08:49
-
-
Save eienf/5582537 to your computer and use it in GitHub Desktop.
Algorithm for convert binary string to decimal integer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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