CHANGEMENT DE BASE

pgassie Messages postés 12 Date d'inscription mardi 28 octobre 2003 Statut Membre Dernière intervention 13 décembre 2006 - 8 déc. 2003 à 23:07
pgassie Messages postés 12 Date d'inscription mardi 28 octobre 2003 Statut Membre Dernière intervention 13 décembre 2006 - 8 déc. 2003 à 23:07
Cette discussion concerne un article du site. Pour la consulter dans son contexte d'origine, cliquez sur le lien ci-dessous.

https://codes-sources.commentcamarche.net/source/18237-changement-de-base

pgassie Messages postés 12 Date d'inscription mardi 28 octobre 2003 Statut Membre Dernière intervention 13 décembre 2006
8 déc. 2003 à 23:07
/* http://www.javafr.com/code.aspx?ID=18237
* Auteur Argel 28/11/2003
* modifié par gassie.philippe@wanadoo.fr
*/
public class Base
{

private final static String symboles="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* private car l'utilisateur n'en a aucun besoin,
final car ne sera jamais modifié,
static car une seule valeur pour toutes les instances de la classe.
Le tout pour une optimisation de la mémoire.
*/
public static String dix2n(int quotient,int base){ //---------Passage Base 10 en Base n
String resul="";
int suite;
while(quotient>0)
{
suite=quotient%base;
resul=symboles.charAt(suite)+resul;
quotient=quotient/base;
}
return resul;
}

public static void main(String[] args)
{int nombre,base;
if (args.length==2){
try{ nombre=new Integer(args[0]).intValue(); // transforme l'argument qui est String vers un int.
base=new Integer(args[1]).intValue();
System.out.println(dix2n(nombre,base));
}
catch (NumberFormatException e){
System.err.println("Usage : java Base doit être suivi de deux nombres en base dix");}


}
else System.err.println("Usage : java Base 10 3 'nombre suivi de la base'.");
}
}


/* § La transformation inverse se fera par la classe Integer, la fonction est :
public static int parseInt(String s,int radix) throws NumberFormatException
EXEMPLE
...
int nombre;
try{
nombre=Integer.parseInt(s, radix));}
catch (NumberFormatException e){ System.err.println(s+" n'est pas une valeur en base "+radix);}
...
§ La fonction proposée est aussi dans la classe Integer,
public static String toString(int i, int radix)
EXEMPLE
...
String nombre;
nombre=Integer.toString(13, 16); // renvoie 'd', faire Integer.toString(13, 16).toUpperCase() pour avoir 'D'.
...

§ La classe Integer est dans java.lang, il n'y a pas d'import à prévoir.
*/
Rejoignez-nous