{
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);
}
/**
* Does test for equality of values/content, shifting the other BitVector by <code>offset</code> to the right.<br>
- * Therefore <code>offset + other.length() <= this.length()</code> needs to be true.
+ * Therefore <code>offset + other.length() <= this.wdith()</code> needs to be true.
*
* @throws ArrayIndexOutOfBoundsException if <code>offset + other.length() > this.length()</code>
*
{
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);
}
+ public long getUnsignedValueLong()
+ {
+ return getUnsignedValue().longValue();
+ }
+
+ /**
+ * Returns the value of the BitVector as BigInteger interpreted as a two's complement number.
+ *
+ * @throws NumberFormatException if the BitVector is not {@link #isBinary() binary}.
+ *
+ * @author Daniel Kirschten
+ */
+ public BigInteger getSignedValue()
+ {
+ BigInteger unsignedValue = getUnsignedValue();
+ if (bits[bits.length - 1] == Bit.ZERO)
+ return unsignedValue;
+ return unsignedValue.subtract(BitVector.of(Bit.ONE, bits.length).getUnsignedValue()).subtract(BigInteger.ONE);// TODO speed this up!
+ }
+
+ public long getSignedValueLong()
+ {
+ return getSignedValue().longValue();
+ }
+
/**
* Parses a String containing solely {@link Bit} symbols (MSB first)
*
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).
*/
}
};
}
+
+ public BitVector reverse()
+ {
+ int length = length();
+ Bit[] other = new Bit[length];
+ for (int i = 0, j = length - 1; i < length; i++, j--)
+ {
+ other[i] = bits[j];
+ }
+ return new BitVector(other);
+ }
}