{
Bit[] values = new Bit[bits];
for (int i = 0; i < bits; i++)
- {
values[bits - i - 1] = Bit.of(value.testBit(i));
- }
return new BitVector(values);
}
{
if (!isBinary())
throw new NumberFormatException(this + " is not binary");
- byte[] bytes = new byte[(bits.length / 8) + 1];
- for (int i = 0; i < bits.length; i++)
+ byte[] bytes = new byte[(bits.length / 8 + (bits.length % 8 == 0 ? 0 : 1)) + 1];
+ for (int i = bits.length - 1; i >= 0; i--)
{
- if (Bit.ONE == bits[i])
+ if (Bit.ONE == bits[bits.length - i - 1])
{
- bytes[i / 8] |= 1 << (i % 8);
+ try
+ {
+ bytes[bytes.length - (i / 8) - 1] |= 1 << (i % 8);
+ }
+ catch (IndexOutOfBoundsException e)
+ {
+ e.printStackTrace();
+ }
}
}
return new BigInteger(bytes);
return new BitVector(values);
}
+ /**
+ * Changes a single Bit using the given operation. This can be used to set, clear or flip bits.
+ *
+ * @param msbIndex index of the MSB to be changed
+ * @param singleBitOperation the operation to perform on that Bit
+ * @return the resulting, new BitVektor
+ */
+ public BitVector withBitChanged(int msbIndex, UnaryOperator<Bit> singleBitOperation)
+ {
+ Bit[] newBits = bits.clone();
+ newBits[msbIndex] = singleBitOperation.apply(newBits[msbIndex]);
+ return new BitVector(newBits);
+ }
+
/**
* Iterate over the {@link Bit}s of the BitVector <b>from MSB to LSB</b> (left to right).
*/