{"record":{"id":"38b41f26ea48aa88","repo":"python/cpython","slug":"cannot-convert-string-of-len-lens-to-int","errorCode":null,"errorMessage":"cannot convert string of len {lenS} to int","messagePattern":"cannot convert string of len (.+?) to int","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Lib/_pylong.py","lineNumber":363,"sourceCode":"    # finite-precision floating point for this, it's possible that the\n    # computed value is a little less than the true value. If the true\n    # value is at - or a little higher than - an integer, we can get an\n    # off-by-1 error too low. So we add 2 instead of 1 if chopping lost\n    # a fraction > 0.9.\n\n    # The \"WASI\" test platform can complain about `len(s)` if it's too\n    # large to fit in its idea of \"an index-sized integer\".\n    lenS = s.__len__()\n    log_ub = lenS * _LOG_10_BASE_256\n    log_ub_as_int = int(log_ub)\n    w = log_ub_as_int + 1 + (log_ub - log_ub_as_int > 0.9)\n    # And what if we've plain exhausted the limits of HW floats? We\n    # could compute the log to any desired precision using `decimal`,\n    # but it's not plausible that anyone will pass a string requiring\n    # trillions of bytes (unless they're just trying to \"break things\").\n    if w.bit_length() >= 46:\n        # \"Only\" had < 53 - 46 = 7 bits to spare in IEEE-754 double.\n        raise ValueError(f\"cannot convert string of len {lenS} to int\")\n    with decimal.localcontext(_unbounded_dec_context) as ctx:\n        D256 = D(256)\n        pow256 = compute_powers(w, D256, BYTELIM, need_hi=True)\n        rpow256 = compute_powers(w, 1 / D256, BYTELIM, need_hi=True)\n        # We're going to do inexact, chopped arithmetic, multiplying by\n        # an approximation to the reciprocal of 256**i. We chop to get a\n        # lower bound on the true integer quotient. Our approximation is\n        # a lower bound, the multiplication is chopped too, and\n        # to_integral_value() is also chopped.\n        ctx.traps[decimal.Inexact] = 0\n        ctx.rounding = decimal.ROUND_DOWN\n        for k, v in pow256.items():\n            # No need to save much more precision in the reciprocal than\n            # the power of 256 has, plus some guard digits to absorb\n            # most relevant rounding errors. This is highly significant:\n            # 1/2**i has the same number of significant decimal digits\n            # as 5**i, generally over twice the number in 2**i,\n            ctx.prec = v.adjusted() + GUARD + 1","sourceCodeStart":345,"sourceCodeEnd":381,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pylong.py#L345-L381","documentation":"Raised by the asymptotically fast int-from-decimal-string path in _pylong (used for huge string conversion via decimal arithmetic) when the input string is so large that estimating its digit count with IEEE-754 doubles loses too much precision: the estimated word count w needs >= 46 bits, leaving fewer than ~7 bits of float mantissa headroom. The message reports the offending string length.","triggerScenarios":"int(huge_string) where huge_string has on the order of 10**13+ characters (trillions of digits) — the guard only trips for absurd inputs; len(s) * _LOG_10_BASE_256 overflows float precision such that w.bit_length() >= 46.","commonSituations":"Almost exclusively adversarial/buggy programs: unvalidated network or decompressed input fed straight into int(); a size/length field misparsed so a multi-terabyte buffer is treated as a number; test fuzzing with giant numeric strings.","solutions":["Validate input length before conversion and reject absurd sizes: if len(s) > 10**8: raise ValueError('number too large')","Cap decompression and read sizes so a crafted blob cannot become a trillion-digit string","Find why such a huge 'number' exists at all — it indicates an upstream parsing bug (reading the wrong field or the wrong file)"],"exampleFix":"# before\nvalue = int(request_data)   # request_data is attacker-controlled, may be huge\n\n# after\nMAX_DIGITS = 10**6\nif len(request_data) > MAX_DIGITS:\n    raise ValueError('numeric input too long')\nvalue = int(request_data)","handlingStrategy":"validation","validationCode":"MAX_DIGITS = 10**8  # 100M digits is already absurd\nif len(s) > MAX_DIGITS:\n    raise ValueError(f'numeric string too long: {len(s)} digits')\nvalue = int(s)","typeGuard":"def is_reasonable_numeric_string(s):\n    return isinstance(s, (str, bytes)) and len(s) <= 10**8","tryCatchPattern":"try:\n    value = int(s)\nexcept ValueError as e:\n    if 'cannot convert string of len' in str(e):\n        raise ValueError('input too large to be a legitimate number') from e\n    raise","preventionTips":["Bound input size before numeric parsing at every trust boundary","Cap decompression output so zip bombs cannot become giant digit strings","Treat a near-trillion-digit 'number' as an upstream parsing bug, not data"],"tags":["python","int","pylong","input-validation","valueerror"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}