Skip to content

Commit 33f60b9

Browse files
committed
gh-71810: fix corner case (length==0) for int.to_bytes()
```pycon >>> (0).to_bytes(0, 'big', signed=True) b'' >>> (-1).to_bytes(0, 'big', signed=True) # was b'' Traceback (most recent call last): File "<python-input-0>", line 1, in <module> (-1).to_bytes(0, 'big', signed=True) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^ OverflowError: int too big to convert ```
1 parent 04c7f36 commit 33f60b9

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

Lib/test/test_long.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1385,6 +1385,8 @@ def equivalent_python(n, length, byteorder, signed=False):
13851385
self.assertEqual((-1).to_bytes(5, 'big', signed=True),
13861386
b'\xff\xff\xff\xff\xff')
13871387
self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1388+
self.assertRaises(OverflowError, (-1).to_bytes, 0, 'big', signed=True)
1389+
self.assertRaises(OverflowError, (-1).to_bytes, 0, 'little', signed=True)
13881390

13891391
# gh-98783
13901392
class SubStr(str):

Objects/longobject.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1209,7 +1209,7 @@ _PyLong_AsByteArray(PyLongObject* v,
12091209
*p = (unsigned char)(accum & 0xff);
12101210
p += pincr;
12111211
}
1212-
else if (j == n && n > 0 && is_signed) {
1212+
else if (j == n && is_signed) {
12131213
/* The main loop filled the byte array exactly, so the code
12141214
just above didn't get to ensure there's a sign bit, and the
12151215
loop below wouldn't add one either. Make sure a sign bit

0 commit comments

Comments
 (0)