// Java-Programm Konvert.java
// Aufgabe 3, AB vom 31.08.2007
// neue Version vom 26.10.2007!
public class Konvert {
static long power(int basis, int n){
// berechnet 2^4 = power(2,4)
long res = 1;
for(int i = 1; i<=n; i++){
res = res * basis;
}
//System.out.println( res );
return res;
} // end of method power
public static void main(String [] args) {
String bZahl = "1001001";
int dZahl, laenge;
char pos;
dZahl = 0;
laenge = bZahl.length();
// bZahl.length() => ergibt Länge des Strings
// im Beispiel: laenge = 7
for (int j=0; j < laenge; j++) {
pos = bZahl.charAt(j);
// zur Kontrolle
//System.out.print( j + " " );
//System.out.println( laenge - j - 1 );
if ( pos == '1' ) {
// VORSICHT: es geht nicht: pos == "1", da "1" ein String ist
dZahl = dZahl + (int) power(2,laenge - j -1 );
// (int) => type casting in Java
}
}
System.out.println( "Binär: " + bZahl + " => Dezimal: " + dZahl );
} // end of main
}// end of class Konvert