Der Flatulator
Member
Perhaps GAF can help me with this:
I'm writing a Bit Utility class for Java that basically serves a a shorthand for implementing things like encryption algorithms.
I'm trying to write a method that essentially acts like Integer#rotateLeft(int,int) (and also rotateRight), As an example, here's part of my unit test:
Here's what I have so far, my test cases have been failing and I've been staring at this code for too long...:
It's a mess to debug. I think I might try and nut it out on my whiteboard.
EDIT: Found the problem. Never mind. Fix for reference:
Typical, soon as I ask for help I solve my own problem.
I'm writing a Bit Utility class for Java that basically serves a a shorthand for implementing things like encryption algorithms.
I'm trying to write a method that essentially acts like Integer#rotateLeft(int,int) (and also rotateRight), As an example, here's part of my unit test:
Code:
int[] testInInt = { 0x1FFF0000, 0x2FFF0000 }
, testOutInt = { 0x00002FFF, 0x00001FFF };
assertArrayEquals(testOutInt, BitUtils.cycleLeft(testInInt, 0x10));
Here's what I have so far, my test cases have been failing and I've been staring at this code for too long...:
Code:
public static int[] cycleLeft(int[] bits, int shift)
{
final int INT_BITS = 0x20;
final int INT_MAX = 0xFFFFFFFF;
final int ARRAY_SIZE = bits.length;
int result[] = new int[ARRAY_SIZE];
int mask[] = new int[ARRAY_SIZE];
int i, mod, div;
shift %= numberOfBits(bits); // (in this case will be %= 32 * ARRAY_SIZE)
mod = shift % INT_BITS;
div = shift / INT_BITS;
for (i = 0; i < ARRAY_SIZE; i++) {
mask[i] = bits[i] & (INT_MAX << (INT_BITS * i + shift));
result[(i - div) % ARRAY_SIZE] = bits[i] << mod;
result[(i + div + ARRAY_SIZE - 1) % ARRAY_SIZE] |= mask[i] >> (INT_BITS - mod);
}
return result;
}
It's a mess to debug. I think I might try and nut it out on my whiteboard.
EDIT: Found the problem. Never mind. Fix for reference:
Code:
for (i = 0; i < ARRAY_SIZE; i++) {
mask[i] = bits[i] & (INT_MAX << (INT_BITS * i + shift));
result[(i - div) % ARRAY_SIZE] = bits[i] << mod;
}
for (i = 0; i < ARRAY_SIZE; i++) {
result[(i + div + ARRAY_SIZE - 1) % ARRAY_SIZE] |= mask[i] >> (INT_BITS - mod);
}
Typical, soon as I ask for help I solve my own problem.