diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py --- a/Lib/test/test_long.py +++ b/Lib/test/test_long.py @@ -1102,6 +1102,7 @@ class LongTest(unittest.TestCase): self.assertEqual((-1).to_bytes(5, 'big', signed=True), b'\xff\xff\xff\xff\xff') self.assertRaises(OverflowError, (1).to_bytes, 0, 'big') + self.assertRaises(OverflowError, (-1).to_bytes, 0, 'big', signed=True) def test_from_bytes(self): def check(tests, byteorder, signed=False): diff --git a/Objects/longobject.c b/Objects/longobject.c --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -890,6 +890,10 @@ _PyLong_AsByteArray(PyLongObject* v, pincr = -1; } + /* fast path for n.to_bytes(0, ...) - this also fixes #27623 */ + if (ndigits && !n) + goto Overflow; + /* Copy over all the Python digits. It's crucial that every Python digit except for the MSD contribute exactly PyLong_SHIFT bits to the total, so first assert that the int is