3 ms·
Doesn't this code actually put q in front of p? That is: ZZZZZZZZ,0000000Q,QQQQQQQQ,QQQQQQQQ,QPPPPPPP With Z still being the width of P?
by twic 5y ago
Doesn't this code actually put q in front of p? That is:
ZZZZZZZZ,0000000Q,QQQQQQQQ,QQQQQQQQ,QPPPPPPP
With Z still being the width of P?
- marginalia_nu 5y agoYeah, that's just me describing the requirements from memory :P
- twic 5y agoAlso, 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.