1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| import java.util.LinkedList;
/**
*
* @author Amaridon Florent
*/
public class BitList extends LinkedList<Boolean>{
/**
* Charge un tableau de byte
* @param bytes
*/
public void loadByteArray(byte[] bytes) {
this.clear();
for (int x = bytes.length - 1; x >= 0; x--) {
int b = bytes[x];
for (int i = 0; i < 8; i++) {
int tmp = b & 0x01;
boolean bool = tmp > 0 ? true : false;
this.addLast(new Boolean(bool));
b = b >> 1;
}
}
}
/**
* Effectue une rotation sur la gauche
* @param start bit de poid le plus faible a prendre en compte dans la rotation
* @param end nombre de bit a faire tourner
*/
public void shiftLeft(int start, int end) {
Boolean tmp = this.remove(start + end - 1);
this.add(start, tmp);
}
/**
* Effectue une rotation sur la droite
* @param start start bit de poid le plus faible a prendre en compte dans la rotation
* @param end nombre de bit a faire tourner
*/
public void shiftRight(int start, int end) {
Boolean tmp = this.remove(start);
this.add(start + end - 1, tmp);
}
/**
*
* @param start index du bit de debut
* @param end index du bit de fin
* @param loops nombre de decalage
*/
public void shiftRight(int start, int end, int loops) {
for (int i = 0; i < loops; i++) {
this.shiftRight(start, end);
}
}
/**
*
* @param start index du bit de debut
* @param end index du bit de fin
* @param loops nombre de decalage
*/
public void shiftLeft(int start, int end, int loops) {
for (int i = 0; i < loops; i++) {
this.shiftLeft(start, end);
}
}
/**
*
* @param index index du bit a modifier
* @param val valeur a lui donnée
* @throws IndexOutOfBoundsException
*/
public void setBit(int index, boolean val) throws IndexOutOfBoundsException{
this.remove(index);
this.add(index, new Boolean(val));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = this.size() - 1; i >= 0; i--) {
int tmp = this.get(i).equals(Boolean.TRUE) ? 1 : 0;
if (((double) (i + 1) % 8 == 0.0) && (i != this.size() - 1)) {
sb.append(' ');
}
sb.append(tmp);
}
return sb.toString();
}
public String toString(int radix) {
byte[] bytes = this.toByteArray();
StringBuilder sb = new StringBuilder("[");
for (byte b : bytes) {
sb.append(Integer.toString(b, radix));
sb.append(", ");
}
sb.replace(sb.length() - 2, sb.length(), "");
sb.append("]");
return sb.toString();
}
public byte[] toByteArray() {
String[] splits = this.toString().split(" ");
byte[] out = new byte[splits.length];
for (int i = 0; i < splits.length; i++) {
out[i] = Byte.valueOf(splits[i], 2);
}
return out;
}
} |
Partager