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);
}
}