begin process at 2010 09 06 05:23:10
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Divers

 > PETITE CLASSE POUR LES OPÉRATIONS BINAIRES

PETITE CLASSE POUR LES OPÉRATIONS BINAIRES


 Information sur la source

 Description

Voilà une petite classe pour réaliser des opérations entre binaires telles que:
01010101 & 00001111 = ?
J'ai essayé de mettre toutes les possibilités de constructeurs, idem pour récupérer le binaire.

Source

  • public class Binary {
  • private boolean[] _value;
  • public Binary(char[] val) {
  • _value = new boolean[val.length];
  • for (int index = 0; index != val.length; ++index) {
  • int tmp = -1;
  • try {
  • tmp = Integer.parseInt(new String(""+val[index]));
  • } catch (Exception e) {
  • throw new IllegalArgumentException("ERROR : This is not a binary String!");
  • }
  • switch (tmp) {
  • case 0 :
  • _value[index] = false;
  • break;
  • case 1:
  • _value[index] = true;
  • break;
  • default:
  • throw new IllegalArgumentException("ERROR : This is not a binary String!");
  • }
  • }
  • }
  • public Binary(boolean[] value) {
  • _value = value.clone();
  • }
  • public Binary(String val) {
  • this(val.toCharArray());
  • }
  • public Binary(int val) {
  • this(Integer.toBinaryString(val));
  • }
  • public Binary() {
  • this(0);
  • }
  • public boolean[] toBooleanArray() {
  • return _value;
  • }
  • public char[] toCharArray() {
  • char[] res = new char[_value.length];
  • for ( int index = 0; index != _value.length; ++index)
  • if (_value[index])
  • res[index] = '1';
  • else
  • res[index] = '0';
  • return res;
  • }
  • public String toString() {
  • return new String(this.toCharArray());
  • }
  • public int toInteger() {
  • int res = 0;
  • for (int index = 0; index != this.length(); ++index)
  • if (_value[index])
  • res += Math.pow(2, this.length() - index -1);
  • return res;
  • }
  • public int length() {
  • return _value.length;
  • }
  • public void setLength(int len) {
  • boolean[] tmp = new boolean[len];
  • for (int index = 0; index != len - this.length(); ++index)
  • tmp[index] = false;
  • for (int index = len - this.length(); index != len; ++index)
  • tmp[index] = _value[index - (len - this.length())];
  • _value = tmp;
  • }
  • public Binary and(Binary bin) {
  • int size = Math.max(this.length(), bin.length());
  • this.setLength(size);
  • bin.setLength(size);
  • boolean[] res = new boolean[size];
  • for (int index = 0; index != size; ++index) {
  • res[index] = this.toBooleanArray()[index] && bin.toBooleanArray()[index];
  • }
  • return new Binary(res);
  • }
  • public Binary or(Binary bin) {
  • int size = Math.max(this.length(), bin.length());
  • this.setLength(size);
  • bin.setLength(size);
  • boolean[] res = new boolean[size];
  • for (int index = 0; index != size; ++index) {
  • res[index] = this.toBooleanArray()[index] || bin.toBooleanArray()[index];
  • }
  • return new Binary(res);
  • }
  • public Binary xor(Binary bin) {
  • int size = Math.max(this.length(), bin.length());
  • this.setLength(size);
  • bin.setLength(size);
  • boolean[] res = new boolean[size];
  • for (int index = 0; index != size; ++index) {
  • res[index] = this.toBooleanArray()[index] ^ bin.toBooleanArray()[index];
  • }
  • return new Binary(res);
  • }
  • public Binary not() {
  • boolean[] res = new boolean[this.length()];
  • for (int index = 0; index != this.length(); ++index) {
  • res[index] = ! _value[index];
  • }
  • return new Binary(res);
  • }
  • }
public class Binary {

	private boolean[] _value;

	public Binary(char[] val) {
		_value = new boolean[val.length];
		for (int index = 0; index != val.length; ++index) {
			int tmp = -1;
			try {
				tmp = Integer.parseInt(new String(""+val[index]));
			} catch (Exception e) {
				throw new IllegalArgumentException("ERROR : This is not a binary String!");
			}
			switch (tmp) {
			case 0 :
				_value[index] = false;
				break;
			case 1:
				_value[index] = true;
				break;
			default:
				throw new IllegalArgumentException("ERROR : This is not a binary String!");
			}
		}
	}

	public Binary(boolean[] value) {
		_value = value.clone();
	}

	public Binary(String val) {
		this(val.toCharArray());
	}

	public Binary(int val) {
		this(Integer.toBinaryString(val));
	}

	public Binary() {
		this(0);
	}

	public boolean[] toBooleanArray() {
		return _value;
	}

	public char[] toCharArray() {
		char[] res = new char[_value.length];
		for ( int index = 0; index != _value.length; ++index)
			if (_value[index])
				res[index] = '1';
			else
				res[index] = '0';
		return res;
	}

	public String toString() {
		return new String(this.toCharArray());
	}

	public int toInteger() {
		int res = 0;
		for (int index = 0; index != this.length(); ++index)
			if (_value[index])
				res += Math.pow(2, this.length() - index -1);
		return res;
	}

	public int length() {
		return _value.length;
	}

	public void setLength(int len) {
		boolean[] tmp = new boolean[len];
		for (int index = 0; index != len - this.length(); ++index)
			tmp[index] = false;
		for (int index = len - this.length(); index != len; ++index)
			tmp[index] = _value[index - (len - this.length())];
		_value = tmp;
	}

	public Binary and(Binary bin) {
		int size = Math.max(this.length(), bin.length());
		this.setLength(size);
		bin.setLength(size);
		boolean[] res = new boolean[size];
		for (int index = 0; index != size; ++index) {
			res[index] = this.toBooleanArray()[index] && bin.toBooleanArray()[index];
		}
		return new Binary(res);
	}

	public Binary or(Binary bin) {
		int size = Math.max(this.length(), bin.length());
		this.setLength(size);
		bin.setLength(size);
		boolean[] res = new boolean[size];
		for (int index = 0; index != size; ++index) {
			res[index] = this.toBooleanArray()[index] || bin.toBooleanArray()[index];
		}
		return new Binary(res);
	}

	public Binary xor(Binary bin) {
		int size = Math.max(this.length(), bin.length());
		this.setLength(size);
		bin.setLength(size);
		boolean[] res = new boolean[size];
		for (int index = 0; index != size; ++index) {
			res[index] = this.toBooleanArray()[index] ^ bin.toBooleanArray()[index];
		}
		return new Binary(res);
	}

	public Binary not() {
		boolean[] res = new boolean[this.length()];
		for (int index = 0; index != this.length(); ++index) {
			res[index] = ! _value[index];
		}
		return new Binary(res);
	}
}

 Conclusion

Exemple pour la question :
Binary bin1 = new Binary("01010101");
Binary bin2 = new Binary("00001111");
Binary res = bin1.and(bin2);
Les opérations supportées sont et (and), ou (or), ou exclusif (xor) et non (not)
Je n'ai pas relevé de bugs...


 Sources de la même categorie

Source avec Zip KIT DE FICHIERS DE PROGRAMMATION par edouard333
Source avec une capture [J2ME] TROUVER LE PGCD DE DEUX NOMBRES par Zestyr
LIRE LES FICHIERS .WAV par Julien39
Source avec Zip Source avec une capture TRADUCTEUR FRANÇAIS --> NERLANDAIS V4 BETA par edouard333
Source avec Zip IA POUR DISCUTER par edouard333

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture CONVERTIR ENTRE LES BASES 10,2,8 ET 16 par 2mohamed2
Source avec Zip TRI DE LIST EN UTILISANT LES ABR par bad_smi
Source avec Zip Source avec une capture REPRÉSENTATION DES EXPRESSIONS ARITHMÉTIQUE SOUS FORME D'ARB... par elvan_2004
Source avec Zip TRI AVEC ARBRE BINAIRE INTERFACE GRAPHIQUE par gulamh
Source avec Zip CONVERTISSEUR HEXA / BIN / OCTAL MVC À 3 VUES par Mathusalem

Commentaires et avis

Commentaire de gilou31120 le 25/09/2006 20:19:30

Petite optimization en vitesse de la méthode toInteger:
Avant :
public int toInteger() {
        int res = 0;
        for (int index = 0; index != this.length(); ++index)
            if (_value[index])
                res += Math.pow(2, this.length() - index -1);
        return res;
    }
Après:
public int toInteger() {
        /* initialize the result with the most significant bit */
        int res = (_value[0] ? 1 : 0);
        for (int index = 1; index < this.length(); index++)
        {
            /* shift left then add one bit */
            res = 2 * res;
            res += (_value[index] ? 1 : 0);
        }
        return res;
    }

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Exploitation du fichier binaire de validation d'un formulaire [ par SONY30 ] J'aimerai savoir si quelqu'un s'était déjà penché sur l'exploitation du fichier binaire en validation d'un formulaire lors d'un transfert d'image par pb de bits [ par Aldee ] Salut,Je veux travailler avec des nombres notés en binaire. Comment j'explique a mon application, que c'est une notation binaire??Si j'écris = 1000111 SWING/font/XML/arbre binaire algo URGENT !!! [ par mkstraits ] salut !à partir d'une interface swing java, on est supposé pouvoir entrer des formules (dans un certain langage de logique) exemple simple: (a.b)=(c+d Representation graphique d'1 arbre binaire [ par smayemba ] Bonjour et bonne année 2003 à tous. Dans le cadre de mon projet,il m'est demandé de représenter graphiquement les arbres binaires gérées par mon soft. Calculette a la con [ par Inc0 ] Voila je voudrai faire une calculette, lors de la compilation il ya un bon nombre d' erreurs, un dizaine, je comprends pas pourquoi , sa m' enerve et Calculette a la con [ par Inc0 ] Voila je voudrai faire une calculette, lors de la compilation il ya un bon nombre d' erreurs, un dizaine, je comprends pas pourquoi , sa m' enerve et Arbre binaire java [ par frances ] J'étude au Portugal. Je doit faire un programme em JAVA d'arbres binaires qui demande a l'utilizateur s'il veux ajouter ou suprimmer une donnée et que arbres RougeNoirs et arbre binaire de recherche [ par marie95 ] projet sur les arbres, créer une classe pour rechercher, ajouter et supprimer Visualiser les arbres Les nombres négatifs et le complément à 2 [ par Tara ] Bonjour à tous,Je désire lire un fichier au format binaire dans lequel chaque bit a une signification précise et donc son importance. A la lecture du Lecture de fichier binaire [ par homerosaur ] Salut à tous.Est-ce que quelqu'un aurais la gentillesse de m'expliquer comment lire un fichier binaire.Mille mercis d'avance


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Septembre 2010
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
27282930   

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,499 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales