Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ede0509

Browse files
committed
_PyLong_AsByteArray: simplify the logic for dealing with the most-
significant digits sign bits. Again no change in semantics.
1 parent ce9de2f commit ede0509

1 file changed

Lines changed: 13 additions & 11 deletions

File tree

Objects/longobject.c

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,6 @@ _PyLong_AsByteArray(PyLongObject* v,
388388
accumbits = 0;
389389
carry = do_twos_comp ? 1 : 0;
390390
for (i = 0; i < ndigits; ++i) {
391-
unsigned int numnewbits = SHIFT;
392391
twodigits thisdigit = v->ob_digit[i];
393392
if (do_twos_comp) {
394393
thisdigit = (thisdigit ^ MASK) + carry;
@@ -399,22 +398,25 @@ _PyLong_AsByteArray(PyLongObject* v,
399398
significant than what's already in accum, so needs to be
400399
prepended to accum. */
401400
accum |= thisdigit << accumbits;
401+
accumbits += SHIFT;
402402

403-
/* How many new bits did we add? The most-significant digit
404-
may be (probably is) at least partly empty. */
403+
/* The most-significant digit may be (probably is) at least
404+
partly empty. */
405405
if (i == ndigits - 1) {
406-
twodigits bitmask = 1 << (SHIFT - 1);
407-
twodigits signbit = do_twos_comp << (SHIFT - 1);
406+
/* Count # of sign bits -- they needn't be stored,
407+
* although for signed conversion we need later to
408+
* make sure at least one sign bit gets stored.
409+
* First shift conceptual sign bit to real sign bit.
410+
*/
411+
stwodigits s = (stwodigits)(thisdigit <<
412+
(8*sizeof(stwodigits) - SHIFT));
408413
unsigned int nsignbits = 0;
409-
while ((thisdigit & bitmask) == signbit && bitmask) {
414+
while ((s < 0) == do_twos_comp && nsignbits < SHIFT) {
410415
++nsignbits;
411-
bitmask >>= 1;
412-
signbit >>= 1;
416+
s <<= 1;
413417
}
414-
assert(nsignbits <= SHIFT);
415-
numnewbits -= nsignbits;
418+
accumbits -= nsignbits;
416419
}
417-
accumbits += numnewbits;
418420

419421
/* Store as many bytes as possible. */
420422
while (accumbits >= 8) {

0 commit comments

Comments
 (0)