5 ms·
Also, it seems to fail if either p or q is 32 bits long - you get zeroes instead of the bits of q. Here's my attempt, which is shorter, and i think quite a bit
by twic 5y ago
Also, it seems to fail if either p or q is 32 bits long - you get zeroes instead of the bits of q.
Here's my attempt, which is shorter, and i think quite a bit clearer:
int pw = bitWidth(p);
int qw = bitWidth(q);
int qpw = qw + pw;
long qp = Integer.toUnsignedLong(q) << pw | Integer.toUnsignedLong(p);
int qpwBytes = ((qpw - 1) / Byte.SIZE) + 1;
byte[] bytes = new byte[qpwBytes + 1];
bytes[0] = (byte) pw;
for (int i = 1; i < bytes.length; i++) {
bytes[i] = (byte) (qp >> (qpwBytes - i) * Byte.SIZE & 0xff);
}
return bytes;
This did take me quite a bit of fiddling to get right - but it wasn't the bit-twiddling, it was the index arithmetic for copying the bytes into the array!
- marginalia_nu 5y agoYeah, the p and q are guaranteed to be positive, should be added. But that is indeed a more elegant solution.