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

Skip to content

Commit 85c0b89

Browse files
bpo-31619: Fixed a ValueError when convert a string with large number of underscores (#3827)
to integer with binary base.
1 parent 1a87de7 commit 85c0b89

3 files changed

Lines changed: 14 additions & 4 deletions

File tree

Lib/test/test_int.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,5 +508,13 @@ def check(s, base=None):
508508
check('123\ud800')
509509
check('123\ud800', 10)
510510

511+
def test_issue31619(self):
512+
self.assertEqual(int('1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1', 2),
513+
0b1010101010101010101010101010101)
514+
self.assertEqual(int('1_2_3_4_5_6_7_0_1_2_3', 8), 0o12345670123)
515+
self.assertEqual(int('1_2_3_4_5_6_7_8_9', 16), 0x123456789)
516+
self.assertEqual(int('1_2_3_4_5_6_7', 32), 1144132807)
517+
518+
511519
if __name__ == "__main__":
512520
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a ValueError when convert a string with large number of underscores
2+
to integer with binary base.

Objects/longobject.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,15 +2057,15 @@ long_from_binary_base(const char **str, int base, PyLongObject **res)
20572057
}
20582058

20592059
*str = p;
2060-
/* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
2061-
n = digits * bits_per_char + PyLong_SHIFT - 1;
2062-
if (n / bits_per_char < p - start) {
2060+
/* n <- the number of Python digits needed,
2061+
= ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2062+
if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
20632063
PyErr_SetString(PyExc_ValueError,
20642064
"int string too large to convert");
20652065
*res = NULL;
20662066
return 0;
20672067
}
2068-
n = n / PyLong_SHIFT;
2068+
n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
20692069
z = _PyLong_New(n);
20702070
if (z == NULL) {
20712071
*res = NULL;

0 commit comments

Comments
 (0)