Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

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...
 

Commentaires et avis

signaler à un administrateur
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...

CalendriCode

Octobre 2008
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Logiciels à télécharger sur le même thème :



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel BAÏSE, 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
Temps d'éxécution de la page : 0,45 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.