Is there a way I can split a BigInteger
into an array of nibbles(4 bit segments)? There is a built in way to get a byte array, BigInteger.toByteArray()
, but not a way to get nibbles.
You can create your own method to do this using the byte array you get from toByteArray()
public static List<Byte> getNibbles(byte[] bytes) {
List<Byte> nibbles = new ArrayList<Byte>();
for (byte b : bytes) {
nibbles.add((byte) (b >> 4));
nibbles.add((byte) ((b & 0x0f)));
}
return nibbles;
}
public static void main(String[] args) {
BigInteger i = BigInteger.valueOf(4798234);
System.out.println(Arrays.toString(i.toByteArray()));
System.out.println(getNibbles(i.toByteArray()));
}
Output
[73, 55, 26]
[4, 9, 3, 7, 1, 10]
Take the byte 55. You're adding the highest 4 bits and the lowest 4 bits to the nibble list.
55 = 00110111
(55 >> 4) = 00000011 (3)
(55 & 0x0f) = 00000111 (7)