Anon
Anon

Reputation: 1

When converting a string to an int, how do I check if there will be overflow?

I am trying to convert a string to a 32-bit int and I want to clamp numbers smaller than -2^31 to -2^31 and numbers bigger than 2^31-1 to 2^31-1.

This is my code so far, but for some reason it is not working.

import sys

if num > sys.maxsize:
   return 2147483647
elif num < -sys.maxsize - 1: 
   return -2147483648

Any help would be appreciated, thank you!

Upvotes: 0

Views: 37

Answers (1)

Adon Bilivit
Adon Bilivit

Reputation: 27033

If your constraints are specifically 32-bit then you should not be referring to sys.maxsize because that will not give you the correct value in a 64-bit environment.

Much easier to use well-known constants.

Therefore:

HI = 2147483647
LO = -2147483648

def convert(s):
    if (i := int(s)) > HI:
        return HI
    return LO if i < LO else i

Upvotes: 0

Related Questions